简体   繁体   English

单击取消按钮时如何消除错误

[英]How to remove error when cancel button is clicked

I have a form inside which i am showing edit,save and cancel button logically, so initially edit button is visible and all inputs are disabled, and when I click on edit I am making my save and cancel button visible and edit not visible.我有一个表单,其中我在逻辑上显示编辑、保存和取消按钮,所以最初编辑按钮是可见的并且所有输入都被禁用,当我单击编辑时,我使我的保存和取消按钮可见,而编辑不可见。

So after filling some data when user click on save I am checking the validation like required fields, so if error then user can see.因此,在用户单击保存时填写一些数据后,我正在检查必填字段等验证,因此如果出现错误,则用户可以看到。

After then on click of edit if user do not want to save then I am filling the data in site for to the initial values, but if there is error on click of save and I am clicking cancel still the error is there it is not going away,之后,如果用户不想保存,则单击编辑,然后我将站点中的数据填充为初始值,但是如果单击保存时出现错误并且我单击取消,则错误仍然存在离开,

What I am doing wrong我做错了什么

I think on click when i am filling my formdata to initial value.当我将表单数据填充为初始值时,我认为点击。

if above point is correct then why error is still visible如果上述观点是正确的,那么为什么错误仍然可见

my code我的代码

import React, { useState, useEffect } from "react";
import "./styles.css";
import { useForm } from "react-hook-form";

// mock for useQuery
const useQuery = query => {
  const [loading, setIsLoading] = useState(true);
  const [data, setData] = useState({});
  useEffect(() => {
    setTimeout(() => {
      setIsLoading(false);
      setData({ firstname: "steve", lastname: "smith" });
    }, 1000);
  }, []);
  return { loading, data };
};

export default function App() {
  const { register, handleSubmit, errors } = useForm();
  const [disabled, setdisabled] = useState(true);
  const [editBtn, seteditBtn] = useState(true);
  const [initialData, setinitialData] = useState({});
  const { loading, data } = useQuery("some qraphql query here"); // getting data from graphql
  const [formData, setFormData] = useState({});

  useEffect(() => {
    setFormData(data);
    setinitialData(data);
  }, [data]);

  const edit = () => {
    setdisabled(false);
    seteditBtn(false);
  };
  const cancel = () => {
    setFormData(initialData);
    setdisabled(true);
    seteditBtn(true);
  };
  const onSubmit = () => {
    console.log(formData);
     };

  const handleChange = e => {
    const name = e.target.name;
    const value = e.target.value;
    console.log(name, value);
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  return (
    <div className="container-fluid">
      <form onSubmit={handleSubmit(onSubmit)}>
        {editBtn === true && (
          <div align="right">
            <button
              className="btn white_color_btn"
              type="button"
              onClick={edit}
            >
              Edit
            </button>
          </div>
        )}
        {editBtn === false && (
          <div>
            <button className="btn white_color_btn" type="submit">
              Save
            </button>
            <button
              className="btn white_color_btn"
              type="submit"
              onClick={cancel}
            >
              Cancel
            </button>
          </div>
        )}

        <div className="row">
          <div className="form-group col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4">
            <input
              type="text"
              id="firstname"
              name="firstname"
              onChange={handleChange}
              value={formData.firstname}
              disabled={disabled}
              ref={register({ required: true })}
            />
            {errors.firstname && (
              <span className="text-danger">first name required</span>
            )}
            <br />
            <label htmlFor="emp_designation">First name</label>
          </div>
          <div className="form-group col-6 col-sm-6 col-md-6 col-lg-4 col-xl-4">
            <input
              type="text"
              id="lastname"
              name="lastname"
              value={formData.lastname}
              onChange={handleChange}
              disabled={disabled}
              ref={register({ required: true })}
            />
            {errors.lastname && (
              <span className="text-danger">last name required</span>
            )}
            <br />
            <label htmlFor="lastname">Lastname</label>
          </div>
        </div>
      </form>
    </div>
  );
}

To check the issue follow this points要检查问题,请遵循以下几点

click on edit -> empty the field -> then click save -> it will throw error -> then click cancel.单击编辑->清空该字段->然后单击保存->它将引发错误->然后单击取消。

on cancel click I want error should go away在取消点击我想要错误应该 go 离开

Working code codesandbox 工作代码代码框

A simple pattern is you set errors in state and clear the values of errors object to null or empty upon clicking cancel Button or when a valid input is typed.一个简单的模式是您在 state 中设置错误并清除错误 object 到 null 的值,或者在单击取消按钮或键入有效输入时为空。 Here you can initialize errors and reset on cancel button's click.在这里,您可以初始化错误并在单击取消按钮时重置。 So you should update errors every time input value is changed or cancel button is clicked.因此,每次更改输入值或单击取消按钮时,您都应该更新错误。

The errors are present because they're managed by useForm .存在错误是因为它们由useForm管理。 The hook exposes a function reset that should fix your problem.该钩子暴露了一个 function reset ,应该可以解决您的问题。 Here is an example that leverage the function.这是一个利用 function 的 示例

const { register, handleSubmit, reset, errors } = useForm();

// ...

const cancel = () => {
  setFormData(initialData);
  setdisabled(true);
  seteditBtn(true);
  reset();
};

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

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