2

我在 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)

有什么办法解决这个问题吗?

谢谢

4

1 回答 1

9

好的,我得到了这个。我忘记了在 useRef 声明中的输入:

const passwordRef = useRef<TextInput>(null)

然后我可以添加一个!标记或检查当前 ref 的存在而不会出现“从不”错误:

onSubmitEditing={() => (passwordRef.current && passwordRef.current.focus())}
于 2020-08-29T22:54:48.047 回答