reactjs - 如何在 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.
解决方案
要重置特定字段,请使用setFieldValue
将 value 设置为空字符串。
setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void
强制设置字段的值。
field
应该与values
您希望更新的密钥匹配。对于创建自定义输入更改处理程序很有用。
例如:
<Formik
initialValues={initialValues}
...
>
{({ setFieldValue }) =>
...
<button type="reset" onClick={() => setFieldValue('fieldName', '')}>
Reset This
</button>
...
要重置所有字段,请使用resetForm
.
resetForm: (nextValues?: Values) => void
强制重置表单。这将清除
errors
andtouched
,设置isSubmitting
为false
,isValidating
tofalse
,并mapPropsToValues
使用当前 WrappedComponent 的道具或作为参数传递的内容重新运行。
例如:
<Formik
initialValues={initialValues}
...
>
{({ resetForm }) =>
...
<button type="reset" onClick={resetForm}>
Reset All
</button>
...
密码沙盒: https ://codesandbox.io/s/7122xmovnq
推荐阅读
- c - 当使用 UDP 进行文件传输(套接字 API)时,检测何时停止从服务器接收数据( recfrom() )
- python - Astral 封装和矢量化
- flutter - 有没有任何flutter升级/更新没有问题?
- typeorm - TypeORM:QueryFailedError:关系不存在
- python - 如何仅为公会制作可切换命令(Discord.py)
- java - 在没有关闭套接字的情况下发送数据
- raytracing - 光线追踪软阴影
- python - qtableview - 如何检测何时使用键盘(而不是通过单击)移动不同的单元格?
- iis - 使用 Windows 身份验证设置具有面向公众的 URL 的 MicroStrategy Web
- flutter - 如何从 Flutter 中的第三页调用第一页的结果?