首页 > 解决方案 > 如何在 Formik 文本字段上添加清除按钮

问题描述

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

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.

标签: reactjsrefformik

解决方案


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

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

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

- Formik 文档

例如:

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

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

resetForm: (nextValues?: Values) => void

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

- Formik 文档

例如:

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

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


推荐阅读