【问题标题】:How can I use state to disable only the button I clicked如何使用状态仅禁用我单击的按钮
【发布时间】:2021-11-29 19:21:55
【问题描述】:

我有一个文件列表和一个下载每个文件的按钮,我创建了一个状态以在用户单击时禁用按钮并在下载开始时启用它。

这是按钮:

<Button disabled={this.state.disabled} onClick={(e) => { e.stopPropagation(); this.isDownload(props)}} />

这是带有下载功能的代码

import React from 'react';
import autoBind from 'react-autobind';

constructor(props) {
  super(props);
  autoBind(this);
}

  async isDownload(file) {
      this.setState({
        disabled: true
      });
      console.log('start the download');
      const document = await this.props.getFile(fileId);
      if (document.statusCode == 200) { 
          this.setState({ disabled: false }) 
      };
  }

这可行,但是它会禁用所有按钮,我只需要禁用我单击的按钮。我该怎么做?

谢谢!

【问题讨论】:

    标签: javascript reactjs binding bind


    【解决方案1】:

    您只有一个状态属性来控制所有按钮,这就是为什么当您在一个按钮中更改它时,它会影响所有按钮。

    您的逻辑是合理的,但是您需要为每个按钮创建一个 disabled 属性,或者创建一个布尔数组,其中索引 0 对应于第一个按钮,索引 1 对应于第二个按钮,等等。

    然后,您的 isDownload 应该会收到您要禁用的按钮的索引,并仅更改该数组元素。

    你的按钮会是这样的:

    <Button disabled={this.state.disabled[0]} onClick={(e) => { e.stopPropagation(); this.isDownload(props, 0)}} />
    

    当然,这是第一个按钮(注意索引 0)。但是,如果所有按钮的逻辑和行为都相似,则应考虑使用数组并通过它映射来呈现对象。查看 JavaScript 的 map 函数,它已经为您提供了迭代的每个元素的索引。

    【讨论】:

    • 抱歉,我不明白如何将地图事件与按钮关联
    【解决方案2】:

    你已经成功了一半。我想问题是每个按钮都共享相同的disabled 状态。这意味着您需要一种唯一标识要禁用的按钮的方法。我希望您能分享更多关于这些按钮如何呈现的信息,但最简单的方法是直接访问按钮。

    <Button
      disabled={this.state.disabled}
      onClick={(e) => {
        e.stopPropagation();
        // Notice we are passing the target directly here
        this.isDownload(props, e.target)
      }}
    />
    

    在您的点击处理程序中:

      async isDownload(file, btn) {
        btn.disabled = true;
        console.log('start the download');
        const document = await this.props.getFile(fileId);
        if (document.statusCode == 200) { 
          btn.disabled = false;
        };
      }
    

    否则,您需要为每个按钮设置一个禁用状态,除非您需要知道应用程序或组件中其他地方的按钮状态,否则您可以直接修改 disabled 属性。请记住,如果在您的示例中请求失败,您不会重新启用它,因此请记住这一点。

    编辑:一个工作示例here

    【讨论】:

    • 感谢您的回答!我只是不明白为什么在 onClick 你使用 e.target 和 btn 函数
    • 查看我从代码和框链接的示例并阅读有关 HTML 事件的一些文档以了解有关 target 的更多信息。
    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 2015-08-06
    • 2017-02-19
    • 2019-03-16
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多