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

How to add a Clear Button on a Formik Textfield

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

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

<Field label="Email" name="email" ref={this.emailInput} onChange={onChange} component={TextField}/>

但是得到这个:

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

您可以尝试在表单中设置一个重置按钮,例如

<form>
 <Field label="Email" name="email" onChange={onChange} component={TextField}/>
 <input type="reset" value="Reset">
</form>

我以示例 here 为例,它必须重置表单中的所有输入

Formik 有一个名为 resetForm 的内置方法,可以像其他 formik 方法一样访问它。在您的表单中,您可能有类似

的内容
<Formik 
  initialValues={something}
  validationSchem={someSchema}
  render={() => {
    ...some form stuff
    }
  }

/>

您可以在该渲染方法中访问 formik 道具并用它们做您想做的事:

<Formik 
  initialValues={something}
  validationSchem={someSchema}
  render={(props) => {
    ...some form stuff
    <button type="button" onClick={() => props.resetForm()}>reset form</button>
    }
  }

/>

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

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

Set the value of a field imperatively. field should match the key of values you wish to update. Useful for creating custom input change handlers.

- Formik Documentation

例如:

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

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

resetForm: (nextValues?: Values) => void

Imperatively reset the form. This will clear errors and touched, set isSubmitting to false, isValidating to false, and rerun mapPropsToValues with the current WrappedComponent's props or what's passed as an argument.

- Formik Documentation

例如:

<Formik 
  initialValues={initialValues}
  ...
>
    {({ resetForm }) =>
        ...
        <button type="reset" onClick={resetForm}>
            Reset All
        </button>
        ...

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