【问题标题】:How to disable a React button conditionally on a state value?如何根据状态值有条件地禁用 React 按钮?
【发布时间】:2016-11-26 20:12:31
【问题描述】:

我添加了一个带有一个输入和一个保存按钮的简单表单。调用 save 函数并按预期工作。

但我现在想在保存按钮上为禁用的逻辑添加一个布尔值。因此,在我当前的页面中,我有一个名为 email 的状态,如果它为空,我想禁用该按钮。

我所做的尝试如下,将{!this.state.email} 传递到按钮的禁用属性中,但它不会禁用保存按钮。类似这个example:

 <Button primary={true} disabled={!this.state.email} onClick={this._onSave}>Save</Button>

我还在 _onBlur 方法中记录了值,我可以看到正在填充电子邮件状态。

问题:

如何将组件状态绑定到按钮禁用属性?

这是我当前组件的要点:

http://hastebin.com/jufahijoza.js

【问题讨论】:

  • 你为什么要使用这样的状态?你不应该那样使用它。状态应该用于视图。只需创建一个变量并根据需要将其设置为 true 或 false。然后用条件语句来判断是真还是假。
  • 在 if 语句中禁用/启用按钮。

标签: reactjs button state


【解决方案1】:

请查看我的 cmets 以获得解释。

    _onBlur(event) {
       //if(true or false)
       // this.refs.myInputButton theres your button now disable/enable it with javascript

this.props.setUserEmail(event.target.value); 
            console.log(this.state.email);     
        }

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2020-05-29
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 2021-01-06
    • 2020-05-16
    • 2021-12-21
    相关资源
    最近更新 更多