简体   繁体   English

根据父输入功能和单击按钮反应禁用和启用按钮

[英]React disable and enable button based on parent input function and click of button

So basically i have a parent component which uses a child button component. 所以基本上我有一个使用子按钮组件的父组件。 Basically currently when the input validation is not correct it will keep the button disabled. 基本上目前当输入验证不正确时,它将保持按钮被禁用。 However now I have tried to disable the button on click. 但是现在我试图在点击时禁用该按钮。 The button is currently a pure component and i started to use hooks but not sure how i can still get the validation running. 该按钮目前是一个纯组件,我开始使用钩子但不知道如何仍然可以运行验证。

Code is below 代码如下

<ChildButton
            onClick={() => {
              this.checkSomething= this.checkCreds();
            }}
            enabled={this.validateInput()}
          />

My pure component currently looks like this: 我的纯组件目前看起来像这样:

export function AButton({ onClick, enabled, text }) {
  const [disabled, setDisabled] = useState(!enabled);

  function handleClick() {
    setDisabled(!disabled);
    //onClick();
  }
  return (
    <Button
      style={{ display: "block", margin: "auto" }}
      id="next-button"
      onClick={handleClick}
      disabled={disabled}
    >
      {text}
    </Button>
  );
}

So i can get the disable button to work in both scenairos. 所以我可以让禁用按钮在两个scenairos中工作。 As the enabled is always being passed down into this pure component so need to keep setting state of it. 因为启用总是被传递到这个纯组件,所以需要保持它的设置状态。

I ended up using useEffect from react hooks 我最终使用了反应钩子中的useEffect

useEffect(() => setDisabled(!enabled), [enabled]);

This will check every time the enabled props is updated from the parent. 这将在每次从父级更新已启用的道具时进行检查。 Similar to how componentDidUpdate would work 与componentDidUpdate的工作方式类似

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

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