使用 TypeScript 在 React Native 上传递引用:(属性) React.MutableRefObject<null>.current: null 对象可能是 'null'.ts(2531)

Passing refs on React Native with TypeScript: (property) React.MutableRefObject<null>.current: null Object is possibly 'null'.ts(2531)

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