Mar*_*mon 3 ref reactjs formik
我想添加一个清除按钮以方便用户:
constructor(props) {
this.emailInput = React.createRef();
}
<Field label="Email" name="email" ref={this.emailInput} onChange={onChange} component={TextField}/>
Run Code Online (Sandbox Code Playgroud)
但是得到这个:
Warning: Function components cannot be given refs. Attempts to access this ref will fail.
要重置特定字段,请使用setFieldValue将值设置为空字符串。
setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void强制设置字段的值。
field应该与values您希望更新的键匹配。用于创建自定义输入更改处理程序。
例如:
<Formik
initialValues={initialValues}
...
>
{({ setFieldValue }) =>
...
<button type="reset" onClick={() => setFieldValue('fieldName', '')}>
Reset This
</button>
...
Run Code Online (Sandbox Code Playgroud)
要重置所有字段,请使用resetForm。
resetForm: (nextValues?: Values) => void当务之急是重置表格。这将清除
errorsandtouched,设置isSubmitting为false,isValidatingtofalse,并mapPropsToValues使用当前 WrappedComponent 的道具或作为参数传递的内容重新运行。
例如:
<Formik
initialValues={initialValues}
...
>
{({ resetForm }) =>
...
<button type="reset" onClick={resetForm}>
Reset All
</button>
...
Run Code Online (Sandbox Code Playgroud)
代码沙盒:https ://codesandbox.io/s/7122xmovnq