我有一个自定义 字段输入 我使用 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 个参数的函数 value
onChangeText
是 (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/