You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何使用state仅禁用被点击的对应下载按钮

问题原因

你当前使用了全局的单一布尔值disabled作为状态,所有下载按钮都绑定了这同一个状态值,所以点击任意按钮修改状态后,所有按钮都会同步触发禁用效果。

解决方案

将状态改为存储正在下载的文件唯一ID集合,每个按钮单独判断自身对应的文件ID是否在下载集合中,来决定是否禁用。

1. 修改state初始化

constructor(props) {
  super(props);
  autoBind(this);
  this.state = {
    // 存储所有处于下载中的文件ID
    downloadingFiles: new Set()
  };
}

2. 修改下载逻辑

点击时将当前文件ID加入下载集合,下载完成(或请求出错)后将对应ID从集合中移除:

async isDownload(file) {
  // 先标记当前文件为下载中
  this.setState(prev => ({
    downloadingFiles: new Set(prev.downloadingFiles).add(file.fileId)
  }));
  console.log('start the download');
  try {
    const document = await this.props.getFile(file.fileId);
    if (document.statusCode == 200) { 
      // 下载成功后移除标记
      this.setState(prev => {
        const newDownloading = new Set(prev.downloadingFiles);
        newDownloading.delete(file.fileId);
        return { downloadingFiles: newDownloading };
      }) 
    };
  } catch (err) {
    // 请求出错也移除标记,避免按钮永久禁用
    this.setState(prev => {
      const newDownloading = new Set(prev.downloadingFiles);
      newDownloading.delete(file.fileId);
      return { downloadingFiles: newDownloading };
    })
  }
}

3. 修改按钮禁用逻辑

每个按钮仅在自身对应的文件ID处于下载集合中时才禁用:

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

注意:需保证每个文件的fileId是全局唯一的标识。

内容的提问来源于stack exchange,提问作者CodeG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:45:03