代码之家  ›  专栏  ›  技术社区  ›  rory-h

反应-复选框输入未正确更新(由于浅合并)

  •  1
  • rory-h  · 技术社区  · 6 年前

    我相信由于浅合并,我的代码中有一些错误,特别是我的复选框,因为它的行为很奇怪。有人能就如何修复它提出一些建议吗?

    state = {
      form: {
        firstName: "",
        lastName: "",
        email: "",
        password: "",
        rememberMe: false
      }
    };
    
      handleChange = e => {
        const { name, value, checked } = e.target;
        const isCheckbox = checked === "checkbox";
        this.setState(prevState => ({
          form: {
            // all other key value pairs of form object
            ...prevState.form,
    
            // update this one specifically
            [name]: isCheckbox ? checked : value
          }
        }));
      };
    

      validateForm = () => {
        const formInputs = ["firstName", "lastName", "email", "password", "rememberMe"];
    
        for (let i = 0; i < formInputs.length; i++) {
          const inputName = formInputs[i];
    
          if (!this.state.form[inputName].length) {
            return false;
          }
        }
    
        return true;
      };
    
      handleSubmit = () => {
        if (this.validateForm()) {
          console.log("Success!");
          console.log(this.state);
        } else {
          console.log("Failure!");
        }
      };
    

    以下是我表格的一部分:

       <form
          className="Form"
          onSubmit={e => {
            e.preventDefault();
            this.handleSubmit();
          }}
        >
          <input name="firstName" onChange={this.handleChange} />
          <input name="lastName" onChange={this.handleChange} />
          <input name="email" onChange={this.handleChange} />
          <input name="password" onChange={this.handleChange} />
          <input
            name="rememberMe"
            type="checkbox"
            checked={this.state.form.rememberMe}
            onChange={this.handleChange}
          />
          <button className="no-padding">Submit</button>
        </form>
    

    提交后获得“成功”,但我的复选框行为异常,保持选中状态。

    1 回复  |  直到 6 年前
        1
  •  2
  •   agenthunt    6 年前

    我认为应该是这样

     const { name, value, checked, type } = e.target;
     const isCheckbox = type === "checkbox";
    

     const { name, value, checked } = e.target;
         const isCheckbox = name === "rememberMe";