繁体   English   中英

如何实现 Formik

[英]How to implement Formik

我用 Formik 创建了以下组件

 const MyTextField = ({ label, ...props }) => { const [field, meta, helpers] = useField(props); return ( <> <label> {label} <input {...field} {...props} /> </label> {meta.touched && meta.error ? ( <div className="error">{meta.error}</div> ) : null} </> ); };

现在我想在不同的组件中使用这个MyTextField

 import { Formik } from 'formik'; export const Search = () => { return ( <Formik> </Formik> ) }

我应该在 Formik 组件中添加什么? 我不想有“提交操作”,我只想有 onChange 行为

编辑

我做了类似的事情,我得到了错误

 export const Search = () => { const onChange = (event: any) => { console.log(event.target.value) } return ( <Formik> <FormTextField name="firstName" type="text" onChange={onChange} /> </Formik > ) }

TS2739: Type '{ children: Element; }' is missing the following properties from type 'FormikConfig<FormikValues>': initialValues, onSubmit

编辑 2

我已经将 MyTxtField 更改为这样的东西

 import { Input } from 'antd'; import { useField, FieldHookConfig } from 'formik'; export const TextInput = ({ ...props }: FieldHookConfig<string>) => { const [field] = useField(props); return <Input {...field} {...props}/>; };

现在我有输入错误:

(alias) class Input
import Input
Type '{ className: string | undefined; ref?: LegacyRef<HTMLInputElement> | undefined; key?: Key | null | undefined; accept?: string | undefined; ... 288 more ...; innerRef?: ((instance: any) => void) | undefined; } | { ...; } | { ...; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Input> & Pick<Readonly<InputProps>, "color" | ... 290 more ... | "bordered"> & InexactPartial<...> & InexactPartial<...>'.
  Type '{ className: string | undefined; ref?: LegacyRef<HTMLInputElement> | undefined; key?: Key | null | undefined; accept?: string | undefined; alt?: string | undefined; ... 287 more ...; innerRef?: ((instance: any) => void) | undefined; }' is not assignable to type 'IntrinsicClassAttributes<Input>'.
    Types of property 'ref' are incompatible.
      Type 'LegacyRef<HTMLInputElement> | undefined' is not assignable to type 'LegacyRef<Input> | undefined'.
        Type '(instance: HTMLInputElement | null) => void' is not assignable to type 'LegacyRef<Input> | undefined'.
          Type '(instance: HTMLInputElement | null) => void' is not assignable to type '(instance: Input | null) => void'.
            Types of parameters 'instance' and 'instance' are incompatible.
              Type 'Input | null' is not assignable to type 'HTMLInputElement | null'.
                Type 'Input' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 329 more.ts(2322)

您必须导入MyTextField组件,然后使用参数渲染它。

<MyTextField name="firstName" type="text" label="First Name" />

如果要编辑默认输入行为,只需将onChange函数传递给组件:

<MyTextField name="firstName" type="text" label="First Name" onChange={onChange} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM