[英]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 ofvalues
you wish to update.field
应与您希望更新的values
的键匹配。 Useful for creating custom input change handlers.用于创建自定义输入更改处理程序。
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
andtouched
, setisSubmitting
tofalse
,isValidating
tofalse
, and rerunmapPropsToValues
with the current WrappedComponent's props or what's passed as an argument.这将清除
errors
和touched
,设置isSubmitting
到false
,isValidating
到false
,然后重新运行mapPropsToValues
当前WrappedComponent的道具或什么作为参数传递。
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>
}
}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.