【问题标题】:Passing refs on React Native with TypeScript: (property) React.MutableRefObject<null>.current: null Object is possibly 'null'.ts(2531)使用 TypeScript 在 React Native 上传递 refs:(属性) React.MutableRefObject<null>.current: null Object is possible is 'null'.ts(2531)
【发布时间】:2020-12-18 11:47:21
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: reactjs typescript react-native typescript-typings react-native-textinput


    【解决方案1】:

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

    const passwordRef = useRef<TextInput>(null)
    

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

    onSubmitEditing={() => (passwordRef.current && passwordRef.current.focus())}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 2022-01-21
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多