问题描述
我在React Native表单上有多个字段,我希望每次用户使用虚拟键盘验证该字段时,焦点就会从一个跳到下一个。
我想出了类似的东西:
<NamedTextInput
name={'email'}
ref={emailRef}
...
onSubmitEditing={() => passwordRef.current.focus()}
/>
<NamedTextInput
name={'password'}
ref={passwordRef}
...
/>
目前,我收到TypeScript错误:
(property) React.MutableRefObject<null>.current: null
Object is possibly 'null'.ts(2531)
Property 'focus' does not exist on type 'never'.ts(2339)
有什么办法解决这个问题吗?
谢谢
解决方法
好,我知道了。我忘记了useRef声明中的输入:
const passwordRef = useRef<TextInput>(null)
然后我可以添加一个!标记或检查当前引用是否存在,而不会出现“从不”错误:
onSubmitEditing={() => (passwordRef.current && passwordRef.current.focus())}