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

时间:2019-05-14 22:19:44

标签: reactjs ref 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.

3 个答案:

答案 0 :(得分:1)

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

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

我以here为例,它必须重置所有输入形式的

答案 1 :(得分:1)

Formik具有一个称为resetForm的内置方法,可以像其他formik方法一样进行访问。在您的表单中,您可能会遇到类似

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

/>

您可以访问该render方法中的formik道具,并使用它们进行所需的操作:

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

/>

答案 2 :(得分:1)

要重置特定字段,请使用setFieldValue将值设置为空字符串。

  

setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void

     

必须设置字段的值。 field应该与您要更新的values的密钥相匹配。对于创建自定义输入更改处理程序很有用。

     

-Formik Documentation

例如:

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

要重置所有字段,请使用resetForm

  

resetForm: (nextValues?: Values) => void

     

立即重置表单。这将清除errorstouched,将isSubmitting设置为false,将isValidating设置为false,然后使用当前的命令重新运行mapPropsToValues WrappedComponent的道具或作为参数传递的东西。

     

-Formik Documentation

例如:

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

Codesandbox:https://codesandbox.io/s/7122xmovnq