我关注了 documentation 的所有内容
并观看了 Ben Awad on YouTube 的教程.而且,我仍然无法让它工作。
const TextField = (props: FieldHookConfig<{}>) => {
const [field] = useField(props);
return (
<div>
<input {...field} {...props}/>
</div>
);
};
我用了
FieldHookConfig
作为 Prop 的类型,因为 useField
期待 string
或 FieldHookConfig
基于 Field.d.ts 文件。然而 typescript 仍然不开心。它在这一行提示
<input {...field} {...props}/>
(property) JSX.IntrinsicElements.input: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
Type '{ ref?: string | ((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined; key?: string | number | undefined; ... 289 more ...; innerRef?: ((instance: any) => void) | undefined; } | { ...; } | { ...; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
Type '{ ref?: string | ((instance: HTMLSelectElement | null) => void) | RefObject<HTMLSelectElement> | null | undefined; key?: string | number | undefined; ... 269 more ...; checked?: boolean | undefined; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
Type '{ ref?: string | ((instance: HTMLSelectElement | null) => void) | RefObject<HTMLSelectElement> | null | undefined; key?: string | number | undefined; ... 269 more ...; checked?: boolean | undefined; }' is not assignable to type 'ClassAttributes<HTMLInputElement>'.
Types of property 'ref' are incompatible.
Type 'string | ((instance: HTMLSelectElement | null) => void) | RefObject<HTMLSelectElement> | null | undefined' is not assignable to type 'string | ((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined'.
Type '(instance: HTMLSelectElement | null) => void' is not assignable to type 'string | ((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined'.
Type '(instance: HTMLSelectElement | null) => void' is not assignable to type '(instance: HTMLInputElement | null) => void'.
Types of parameters 'instance' and 'instance' are incompatible.
Type 'HTMLInputElement | null' is not assignable to type 'HTMLSelectElement | null'.
Type 'HTMLInputElement' is missing the following properties from type 'HTMLSelectElement': length, options, selectedIndex, selectedOptions, and 4 more.ts(2322)
最佳答案
有两个问题,第一,不能传播props
<input>
上的变量元素,由于不兼容的类型(如错误中指定)。其次,FieldHookConfig
的泛型类型不应该是 {}
, 而应该是 string
所以要修复它,假设您使用的是 <TextField>
像这样的元素
<TextField
name="firstName"
type="text"
placeholder="Jane"
/>
然后在你的TextField
里面定义,你会写const TextField = (props: FieldHookConfig<string>) => {
const [field] = useField(props);
return (
<div>
{/* no need to pass the name field because Formik will accept
that prop internally and pass it to the field variable */}
<input {...field} placeholder={props.placeholder} type={props.type} />
</div>
);
};
关于reactjs - 如何在 typescript 中正确使用 Formik 的 useField 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61089182/