如何正确设置/使用 ref 为 typescript + react native 中的主题功能组件

问题描述

主要目标:我有两个 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

解决方法

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

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={() => {}} />
    </>);
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...