【问题标题】:disable button in reactjsreactjs中的禁用按钮
【发布时间】:2018-12-01 08:32:38
【问题描述】:

我有一系列执行内部逻辑的按钮(没有不依赖于输入的表单),但异步调用函数。我想一键禁用按钮,并在onclick() 方法上尝试了几件事,但一直出错。

代码如下所示:

{ this.state.isEthTransferVisible && <button id="button"
                  onClick={() => { parseAddress(this.state.sc);}, this.handleTransferFromEthereum}>Check Balances</button>
} 

这是从onclick 中调用的函数

async handleTransferFromEthereum(){
  await parseAddress(this.state.sc)
    this.setState(prevState => ({
         isEthTransferVisible: !prevState.isEthTransferVisible,
         isGoDeployedVisible: !prevState.isGoDeployedVisible
    }));
}

【问题讨论】:

    标签: reactjs button disable


    【解决方案1】:

    添加另一个状态变量,例如this.isEthTransferEnabled(默认为true)。将您的按钮更改为:

    { this.state.isEthTransferVisible && <button id="button"
                      disabled={this.state.isEthTransferEnabled}
                      onClick={() => { parseAddress(this.state.sc);}, this.handleTransferFromEthereum}>Check Balances</button>
    }
    

    并更改您的 handleTransferFromEthereum 方法:

    async handleTransferFromEthereum(){
      this.setState({ isEthTransferEnabled: false });
      await parseAddress(this.state.sc)
        this.setState(prevState => ({
             isEthTransferVisible: !prevState.isEthTransferVisible,
             isEthTransferEnabled: true,
             isGoDeployedVisible: !prevState.isGoDeployedVisible
        }));
    }
    

    【讨论】:

    • 我一定是遗漏了一些东西,因为它无法正常工作。我添加了constructor(props) { super(props); this.state = {isEthTransferEnabled: true} },但它不起作用
    【解决方案2】:
    onClick={() => { parseAddress(this.state.sc);}, this.handleTransferFromEthereum}
    

    语法错误?应该是:

    onClick={() => { 
      parseAddress(this.state.sc);
      this.handleTransferFromEthereum();
    }}
    

    【讨论】:

    • 问题中的代码运行良好,我要求在单击按钮时禁用该按钮。你的回答没有说​​明如何做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2023-01-30
    • 2021-12-31
    • 2022-06-23
    相关资源
    最近更新 更多