繁体   English   中英

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

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

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

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将值设置为空字符串。

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

当务之急是重置表格。 这将清除errorstouched ,设置isSubmittingfalseisValidatingfalse ,然后重新运行mapPropsToValues当前WrappedComponent的道具或什么作为参数传递。

- Formik 文档

例如:

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

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

Formik 有一个名为resetForm的内置方法,可以像其他 formik 方法一样访问它。 在你的形式中,你可能有类似的东西

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

/>

您可以访问该渲染方法中的 formik 道具并使用它们执行您想要的操作:

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

/>

您可以尝试在表单中设置重置按钮,例如

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

我以这里为例,它必须重置表单中的所有输入

暂无
暂无

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

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