javascript - 更改 onChangeText 后无法在输入字段中输入

标签 javascript reactjs typescript react-native formik

我有一个自定义 字段输入 我使用 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

最佳答案

onChangeText是一个接受 1 个参数的函数 valueonChangeText(value: string) => 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

关于javascript - 更改 onChangeText 后无法在输入字段中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63768668/

相关文章:

javascript - Bootstrap datetimepicker - 从给定时间步进

reactjs - 用完整的圆角 react native 日历周期标记

reactjs - 功能组件的 PropTypes.instanceOf 不起作用

javascript 不允许我使用模数? %?

javascript - ngFor 不处理子属性(property)?

javascript - 按特定属性的最大值过滤数组元素

javascript - Google Charts API 数据表单元格颜色

javascript - 闰年功能不起作用

android - React Native 左对齐图标,文本居中

html - 在 Angular 中选择时如何检索 id 和名称?