简体   繁体   English

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

[英]How to add a Clear Button on a Formik Textfield

I want to add a Clear Button as a convenience to users:我想添加一个清除按钮以方便用户:

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

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

But get this:但是得到这个:

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

To reset particular fields, use setFieldValue to set value to an empty string.要重置特定字段,请使用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. field应与您希望更新的values的键匹配。 Useful for creating custom input change handlers.用于创建自定义输入更改处理程序。

- Formik Documentation - Formik 文档

Eg:例如:

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

To reset all fields, use resetForm .要重置所有字段,请使用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.这将清除errorstouched ,设置isSubmittingfalseisValidatingfalse ,然后重新运行mapPropsToValues当前WrappedComponent的道具或什么作为参数传递。

- Formik Documentation - Formik 文档

Eg:例如:

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

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

Formik has a built in method called resetForm which can be accessed like the other formik methods. Formik 有一个名为resetForm的内置方法,可以像其他 formik 方法一样访问它。 In your form you probably have something like在你的形式中,你可能有类似的东西

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

/>

you can access the formik props inside that render method and do what you want with them:您可以访问该渲染方法中的 formik 道具并使用它们执行您想要的操作:

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

/>

you can try to set a reset button in your form, eg您可以尝试在表单中设置重置按钮,例如

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

I took the example here , it has to reset all of the inputs in the form我以这里为例,它必须重置表单中的所有输入

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

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