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

React中如何实现按钮具备复选框可选中、取消选中的功能

解决方案

问题根因

你当前的点击处理逻辑仅实现了「新增选中项」的操作,没有判断点击项是否已处于选中状态,因此无法触发取消选中的逻辑。

核心修改

你只需要调整handleSelectedValue函数的逻辑,增加选中状态判断即可:

const handleSelectedValue = (reason: any) => {
  setSelectedValues(prev => {
    // 校验当前点击项是否已被选中
    const hasSelected = prev.some(item => item.id === reason.id);
    if (hasSelected) {
      // 已选中时过滤掉当前项,实现取消选中
      return prev.filter(item => item.id !== reason.id);
    } else {
      // 未选中时追加当前项到选中列表
      return [...prev, reason];
    }
  });
};

可选优化

你现有的checkId函数通过map生成新数组再判断是否包含目标id,会产生不必要的性能消耗,可调整为直接用some方法判断:

const checkId = (id: number) => {
  return selectedValues.some(item => item.id === id);
};

其余JSX代码无需修改,选中、取消选中的样式会自动跟随selectedValues的状态变化生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:15:03