Formik - 确认后如何重置表格

新手上路,请多包涵

Formik 中,如何让 Reset 按钮 在确认后才 重置表单?

即使您单击取消,我下面的代码仍会重置表单。

 var handleReset = (values, formProps) => {
    return window.confirm('Reset?'); // still resets after you Cancel :(
};

return (
  <Formik onReset={handleReset}>
    {(formProps) => {
      return (
        <Form>
          ...
          <button type='reset'>Reset</button>
        </Form>
      )}}
  </Formik>
);

原文由 Aximili 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 553
2 个回答

我不完全确定,但我认为您将不得不编写自己的重置功能,而无需使用 reset 类型的按钮。像这样的东西:

 const handleReset = (resetForm) => {
  if (window.confirm('Reset?')) {
    resetForm();
  }
};

function Example() {
  return (
    <Formik initialValues={{ value: 1 }}>
      {formProps => {
        return (
          <Form>
            <Field name="value" type="number" />
            <button
              onClick={handleReset.bind(null, formProps.resetForm)}
              type="button"
            >
              Reset
            </button>
          </Form>
        );
      }}
    </Formik>
  );
}

如果您真的想使用 onReset ,我认为唯一的方法是抛出错误。 Formik 源代码 似乎表明 resetForm() 无论您的 onReset() 函数返回什么都会被调用。

 const handleReset = () => {
  if (!window.confirm('Reset?')) {
    throw new Error('Cancel reset');
  }
};

function Example() {
  return (
    <Formik initialValues={{ value: 1 }} onReset={handleReset}>
      {formProps => {
        return (
          <Form>
            <Field name="value" type="number" />
            <button type="reset">
              Reset
            </button>
          </Form>
        );
      }}
    </Formik>
  );
}

尽管我个人仍然会使用第一个解决方案。

原文由 Ciarán Tobin 发布,翻译遵循 CC BY-SA 4.0 许可协议

您好@Aximili,您可以在 onSubmit 中使用 resetForm

 onSubmit={(values, { resetForm }) => {

      // do your stuff
      resetForm();

}}

什么 resetForm 可以做什么?

强制重置表单。这将清除错误和触摸,将 isSubmitting 设置为 false,将 isValidating 设置为 false,并使用当前 WrappedComponent 的 props 或作为参数传递的内容重新运行 mapPropsToValues。后者对于在 componentWillReceiveProps 中调用 resetForm 很有用。

原文由 patelarpan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进