【问题标题】:How to setup/use ref correctly for a themed functional component in typescript + react native如何在 typescript + react native 中为主题功能组件正确设置/使用 ref
【发布时间】:2021-05-18 20:20:46
【问题描述】:

主要目标:我有两个 TextInput,我想模拟返回单击第一个 textInput 以将焦点设置到下一个 textInput。

让我们从设置开始(使用打字稿)

我有一个带有一些颜色设置的主题 TextInput,如下所示。如果提供,我设置/使用 forwardRef 来传递 ref。在我能读到的内容中,这似乎是正确的方法。但也许这是错误的。

export type TextInputProps = ThemeProps & RNTextInput['props'];

export const TextInput = React.forwardRef<RNTextInput, TextInputProps>((props, ref) => {
...
return <RNTextInput style={[{ backgroundColor, color }, style]} {...otherProps} ref={ref} />;
}

现在在我的屏幕上,我正在使用这个对象,并且在完成第一次输入时,我想将焦点放在这个对象上。代码看起来像这样..

const inputSecound = React.useRef<typeof TextInput>();
const handleFirstTextComplete = () => {
    inputSecound.current.focus() // This does not work
}
...
<TextInput onSubmitEditing={handleFirstTextComplete} ...>
<TextInput ... ref={inputSecound}> //This also complains

知道如何在功能组件+自定义组件+打字稿中正确实现这一点。

如果您想查看完整的设置,可以在此处获取样品小吃。 https://snack.expo.io/@varesh.tapadia/useref-and-useforwardref

【问题讨论】:

  • 如果解决了您的问题,请接受答案

标签: typescript react-native use-ref react-forwardref


【解决方案1】:

这应该可以解决您的问题。

interface CustomInputProps {
    handleCompletion: () => void;
}

const CustomInput = React.forwardRef<HTMLInputElement, CustomInputProps>((props, ref) => {
    return <input ref={ref}/>;
});

const Parent = () => {
    const secondInputRef = useRef<HTMLInputElement>(null);
    const handleCompletion = () => {
        secondInputRef?.current?.focus();
    }
    return (<>
        <CustomInput handleCompletion={handleCompletion} />
        <CustomInput ref={secondInputRef} handleCompletion={() => {}} />
    </>);
}

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2020-08-23
    • 2021-12-07
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多