如何在 TypeScript + React Native 中为主题化函数组件正确设置/使用 ref
主要目标:我有两个文本输入框,我想在第一个文本输入框上模拟回车点击,以将焦点设置到下一个文本输入框。
让我们从设置开始(使用 TypeScript)
我有一个带有一些颜色设置的主题化 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
有什么方法可以在函数组件 + 自定义组件 + TypeScript 中正确地实现这一点吗?
如果你想看到完整的设置效果,这里提供一个示例小吃。https://snack.expo.io/@varesh.tapadia/useref-and-useforwardref
答案#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={() => {}} />
</>);
}
