【问题标题】:How to type properly with ref?如何使用 ref 正确输入?
【发布时间】:2021-09-28 15:33:06
【问题描述】:

我有一个简单的自定义组件,如下所示

import {View, TextInput} from 'react-native'

interface ICustomProps extends TextInputProps {
  iconName?: WhateverType;
}

const CustomInput: React.FC<ICustomProps> = React.forwardRef((props, ref) => {
  const [someState, setSomeState] = useState(false);

  return (
    <View>
      {props.iconName && renderIcon()}
      <TextInput 
        ref={ref}
        {...props}
      />
    </View>
  )
})

export default CustomInput

使用上面的代码,我希望它能够工作,因为我想为 textinput 实现自动对焦,但是,当我定义 ref 时,我遇到了错误

No overload matches this call.
  Overload 1 of 2, '(props: TextInputProps | Readonly<TextInputProps>): TextInput', gave the following error.
    Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<TextInput> | undefined'.
      Type 'MutableRefObject<unknown>' is not assignable to type 'LegacyRef<TextInput> | undefined'.
        Type 'MutableRefObject<unknown>' is not assignable to type 'RefObject<TextInput>'.
          Types of property 'current' are incompatible.
            Type 'unknown' is not assignable to type 'TextInput | null'.
              Type 'unknown' is not assignable to type 'TextInput'.
  Overload 2 of 2, '(props: TextInputProps, context: any): TextInput', gave the following error.

似乎无法理解组件的哪一部分出错了,在这里感谢一些帮助

【问题讨论】:

    标签: javascript reactjs typescript react-native ref


    【解决方案1】:

    您应该将 ref 作为 inputRef 的道具传递。

    interface ICustomProps extends TextInputProps {
      iconName?: WhateverType;
    }
    
    const CustomInput: React.FC<ICustomProps> = React.forwardRef((props, ref) => {
      const [someState, setSomeState] = useState(false);
    
      return (
        <View>
          {props.iconName && renderIcon()}
          <TextInput 
            inputRef={ref}
            {...props}
          />
        </View>
      )
    })
    
    export default CustomInput
    

    【讨论】:

    • 感谢您的帮助,但我认为 TextInput 没有 inputRef
    • 我以为你使用了 material-ui 组件。你能解释一下 TextInput 组件吗? @艾萨克
    • 抱歉漏掉了,TextInputreact-native提供的原生组件,我会把它包含在上面的代码中
    【解决方案2】:
    const CustomInput = React.forwardRef<TextInput, ICustomProps>((props, ref) => { ... }
    

    向转发引用添加类型会有帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-09
      • 2014-02-03
      • 1970-01-01
      • 2019-12-12
      • 2017-06-23
      • 2015-11-29
      • 1970-01-01
      • 2014-07-24
      相关资源
      最近更新 更多