如何在 Formik 文本字段上添加清除按钮

Mar*_*mon 3 ref reactjs formik

我想添加一个清除按钮以方便用户:

constructor(props) {
    this.emailInput = React.createRef();
}

<Field label="Email" name="email" ref={this.emailInput} onChange={onChange} component={TextField}/>
Run Code Online (Sandbox Code Playgroud)

但是得到这个:

Warning: Function components cannot be given refs. Attempts to access this ref will fail.

Dan*_*jay 8

要重置特定字段,请使用setFieldValue将值设置为空字符串。

setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void

强制设置字段的值。field应该与values您希望更新的键匹配。用于创建自定义输入更改处理程序。

- Formik 文档

例如:

<Formik 
  initialValues={initialValues}
  ...
>
    {({ setFieldValue }) =>
        ...
        <button type="reset" onClick={() => setFieldValue('fieldName', '')}>
            Reset This
        </button>
        ...
Run Code Online (Sandbox Code Playgroud)

要重置所有字段,请使用resetForm

resetForm: (nextValues?: Values) => void

当务之急是重置表格。这将清除errorsand touched,设置isSubmittingfalseisValidatingto false,并mapPropsToValues使用当前 WrappedComponent 的道具或作为参数传递的内容重新运行。

- Formik 文档

例如:

<Formik 
  initialValues={initialValues}
  ...
>
    {({ resetForm }) =>
        ...
        <button type="reset" onClick={resetForm}>
            Reset All
        </button>
        ...
Run Code Online (Sandbox Code Playgroud)

代码沙盒:https ://codesandbox.io/s/7122xmovnq