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

Xii*_*ryo 2 typescript reactjs react-native typescript-typings react-native-textinput

我的 React Native 表单上有几个字段,我希望每次用户使用虚拟键盘验证该字段时,焦点都会从一个字段跳到下一个字段。

我想出了这样的东西:

        <NamedTextInput
          name={'email'}
          ref={emailRef}
          ...
          onSubmitEditing={() => passwordRef.current.focus()}
        />
        
        <NamedTextInput
          name={'password'}
          ref={passwordRef}
          ...
        />
Run Code Online (Sandbox Code Playgroud)

目前我收到一个 TypeScript 错误:

(property) React.MutableRefObject<null>.current: null
Object is possibly 'null'.ts(2531)
Run Code Online (Sandbox Code Playgroud)

我尝试添加!和 ?标记但它结束为:

Property 'focus' does not exist on type 'never'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

有办法解决这个问题吗?

谢谢

Xii*_*ryo 10

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

const passwordRef = useRef<TextInput>(null)
Run Code Online (Sandbox Code Playgroud)

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

onSubmitEditing={() => (passwordRef.current && passwordRef.current.focus())}
Run Code Online (Sandbox Code Playgroud)