【问题标题】:How to add a Clear Button on a Formik Textfield如何在 Formik 文本字段上添加清除按钮
【发布时间】:2019-05-14 22:19:44
【问题描述】:

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

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.

【问题讨论】:

    标签: reactjs ref formik


    【解决方案1】:

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

    setFieldValue: (field: string, value: any, shouldValidate?: boolean) =&gt; void

    强制设置字段的值。 field 应该与您希望更新的 values 的键匹配。对于创建自定义输入更改处理程序很有用。

    -Formik Documentation

    例如:

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

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

    resetForm: (nextValues?: Values) =&gt; void

    强制重置表单。这将清除errorstouched,将isSubmitting 设置为false,将isValidating 设置为false,并使用当前 WrappedComponent 的 props 或作为参数传递的内容重新运行 mapPropsToValues

    -Formik Documentation

    例如:

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

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

    【讨论】:

      【解决方案2】:

      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>
          }
        }
      
      />
      

      【讨论】:

      • 谢谢,但正在寻找用户输入的文本,清除每个文本字段上的 X 按钮。
      • 在这种情况下,您可以将setFieldValue 函数与您的字段名称一起使用
      【解决方案3】:

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

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

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

      【讨论】:

      • @Maksym 这不会重置 Formik 表单。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多