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

如何用ReactJS函数式组件实现点击Li切换复选框及样式效果

React函数式组件实现复选框列表交互

实现思路

React采用数据驱动视图模式,通过useState钩子维护每个列表项的选中状态,替代原生JS直接操作DOM的方式,确保状态与视图同步。

组件代码

import { useState } from 'react';

const CheckboxList = () => {
  // 初始化所有项的选中状态为未选中
  const [checkedItems, setCheckedItems] = useState({
    item1: false,
    item2: false,
    item3: false,
    item4: false,
    item5: false
  });

  // 切换指定项的选中状态
  const toggleItem = (itemId) => {
    setCheckedItems(prevState => ({
      ...prevState,
      [itemId]: !prevState[itemId]
    }));
  };

  // 列表项数据集合
  const items = [
    { id: 'item1', label: 'Item 1' },
    { id: 'item2', label: 'Item 2' },
    { id: 'item3', label: 'Item 3' },
    { id: 'item4', label: 'Item 4' },
    { id: 'item5', label: 'Item 5' }
  ];

  return (
    <ul>
      {items.map(item => (
        <li
          key={item.id}
          className={`my-li ${checkedItems[item.id] ? 'active' : ''}`}
          onClick={() => toggleItem(item.id)}
        >
          <label htmlFor={item.id}>{item.label}</label>
          <input
            className="my-cbx"
            type="checkbox"
            id={item.id}
            checked={checkedItems[item.id]}
            onChange={(e) => e.stopPropagation()}
          />
        </li>
      ))}
    </ul>
  );
};

export default CheckboxList;

样式代码

ul li {
    list-style: none;
    padding: 5px 20px;
    border: 1px solid #ccc;
    width: 200px;
    cursor: pointer;
}
.my-li.active{
    background: rgb(179, 131, 224);
    color: #fff;
}

关键细节说明

  • 状态管理:通过useState存储每个项的选中状态,修改状态时使用函数式更新,确保基于最新状态修改。
  • 事件处理:点击li时触发toggleItem切换对应项的状态;复选框添加onChange事件阻止冒泡,避免点击复选框时重复触发li的点击事件。
  • 样式控制:通过模板字符串动态为li添加active类,实现选中时的背景色变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:35:27