【问题标题】:can't type in Input field after changing onChangeText更改 onChangeText 后无法在输入字段中输入
【发布时间】:2020-12-25 08:23:35
【问题描述】:

我有一个自定义 FieldInput 图标,我在其中使用 Native Base 的输入组件。我用它来验证 Formik。当我这样使用它时:

 onChangeText={handleChange(fieldType)}

一切似乎都正常,但我在 onChangeText 上收到一个错误

  Overload 1 of 2, '(props: Readonly<Input>): Input', gave the following error.
    Type 'void' is not assignable to type '((text: string) => void) | undefined'.

当我把它改成

 onChangeText={()=>handleChange(fieldType)}

错误消失了,但我的输入字段停止工作。我不能再输入它。我究竟做错了什么?我的组件如下所示:

type FieldInputProps = React.PropsWithRef<{
  handleChange: (e: string) => void;
  value: string;
  fieldType: string;
  placeholderText?: string;
  style?: object;
  rounded?: boolean;
}>;


export const FieldInput = React.forwardRef<Input, FieldInputProps>(({
  handleChange,
  fieldType,
  placeholderText,
  value,
  style,
  rounded,
}, ref) => {

  return (
    <Item rounded={rounded} style={[styles.inputItem, style]}>
      <Input 
        ref={ref}
        autoFocus={true}
        autoCapitalize="none"
        placeholder={placeholderText}
        keyboardType="default"
        onChangeText={handleChange(fieldType)}
        value={value}
       />
      </Item>
  );
});

代码沙盒: https://snack.expo.io/@nhammad/carefree-cereal

【问题讨论】:

  • 您的 fieldType 未在箭头函数中定义。尝试发送事件。
  • 你的意思是这样的? (fieldType)=&gt;handleChange(fieldType),我也试过了,但也没有用。你可以试试codesandbox吗? @kingneo

标签: javascript reactjs typescript react-native formik


【解决方案1】:

onChangeText 是一个接受 1 个参数 value 的函数

onChangeText(value: string) =&gt; void

所以你只需要像下面的例子一样使用onChangeTextCallback

 // ✅ Right way to do it!✅ 

const [value, setValue] = useState<string>('')

<TextInput value={value} onChangeText={setValue} />

// or onChangeText={(newValue: string) => setValue(newValue)}

// Your code
// ❌ Wrong way to do it! ❌

onChangeText={()=>handleChange(fieldType)}
// You forget about value here
// onChangeText={(value: string)=> handleChange(fieldType)}
// You need to provide value to your changing value callback

如果对你有帮助,请告诉我!?‍♂️

更新:

查看链接->https://snack.expo.io/bLEsPJXPS

【讨论】:

  • 不,这对我没有帮助。我已经按照你的建议去做了。即使我使用onChangeTextCallback,仍然存在重载错误。你看过我的代码或沙箱了吗?
  • 是的,我做了并修复了所有东西 -> snack.expo.io/bLEsPJXPS
  • 如果对你有帮助请告诉我
  • 所以主要问题是我在 onChange 上执行handleChange(fieldType),而不是首先将handleChange('input') 传递给 FieldInput 组件?我不明白这是如何解决问题的。他们不一样吗?
  • 正如我在文件FieldInput.tsx, line 41onChangeText={()=&gt;handleChange(fieldType)} 中所说,您没有将TextInputvalue 传递给handleChange 函数,请检查此处的1 个示例reactnative.dev/docs/textinput
猜你喜欢
  • 2019-12-27
  • 2019-12-02
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
相关资源
最近更新 更多