将设置按钮反应为禁用状态

React set button to disabled with state

我在一个基于 React class 的组件中,在我的状态下 属性 是这样的:

  state = {
    controls: {
      email: {
        validation: {
          required: true,
          isEmail: true
        },
        invalid: false,
      },
      password: {
        validation: {
          required: true,
          minLength: 6
        },
        invalid: true,
      },
      disabledSubmit: true,
    }
  };

我有一个从输入组件触发的 inputChangedHandler:

  inputChangedHandler = (event, controlName) => {
    console.log("[STATE]", this.state.controls);
    const updatedControls = {
      ...this.state.controls,
      [controlName]: {
        ...this.state.controls[controlName],
        value: event.target.value,
        invalid: !this.checkValidity(
          event.target.value,
          this.state.controls[controlName].validation
        )
      },
      touched: true
    };

    console.log("[UPDATEDCONTROLS]", updatedControls);
    this.setState({ controls: updatedControls }, () => {
      this.disabledSubmitHandler();
    });
  };

还有一个应该从我的 inputChangedHandler 中调用的 disabledSubmitHandler:

  disabledSubmitHandler() {
    if (
      !this.state.controls["email"].invalid &&
      !this.state.controls["password"].invalid
    ) {
      this.setState(
        { disabledSubmit: true },
        console.log("[DISABLEDHANDLER] TRUE")
      );
    }
  }

道具是在我的 JSX 按钮组件上设置的,如下所示:

<Button
                            value="submit"
                            clicked={this.submitHandler}
                            disabled={this.state.disabledSubmit}
                          />

这不起作用,但我不确定发生了什么?

我想也许这一点似乎需要修复:

disabledSubmitHandler() {
    if (
      !this.state.controls["email"].invalid && //if email is not invalid
      !this.state.controls["password"].invalid //if password is not invalid
    ) {
      this.setState(
        { disabledSubmit: true },
        console.log("[DISABLEDHANDLER] TRUE")
      );
    }
  }

该代码表示​​如果电子邮件和密码有效,则禁用输入。我觉得应该是:

disabledSubmitHandler() {
    if (
      !this.state.controls["email"].invalid &&
      !this.state.controls["password"].invalid
    ) {
      this.setState(
        { disabledSubmit: false },
        console.log("[DISABLEDHANDLER] FALSE")
      );
    }
  }

如@an0nym0us 所述,disabledSubmit 嵌套在 controls 中。

此外,附带说明一下,您调用一个设置状态的函数似乎有点奇怪,只是调用另一个在该函数内设置状态的函数,作为设置状态的回调(inputChangedHandler 调用 disabledSubmitHandler'). It seems you could call that disabled check from withininputChangedHandlerpassing it yourupdatedControls, and return true/false fordisabledSubmit, resulting in a single call tosetState`