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

React JS中父项与子项的复选框联动逻辑实现求助

React品牌与车型复选框联动实现

需求

  • 勾选品牌复选框:显示并勾选该品牌下所有车型
  • 取消品牌复选框:隐藏该品牌下所有车型
  • 取消品牌下任意车型勾选:品牌复选框自动取消勾选

数据结构

[
  {
    display: "HYUNDAI",
    status: false,
    filter: {
      key: "make",
      value: "hyundai",
    },
    count: 292,
    children: [
      {
        display: "Grand i10",
        status: false,
        filter: {
          key: "model",
          value: "grand i10",
        },
        count: 81,
      },
      {
        display: "CRETA",
        status: false,
        filter: {
          key: "model",
          value: "creta",
        },
        count: 47,
      },
      {
        display: "Elite i20",
        status: false,
        filter: {
          key: "model",
          value: "elite i20",
        },
        count: 44,
      },
    ],
  },
];

修正后的完整代码

import React, { useState, useEffect } from "react";
import "./App.css";
import carData from './data.json';

const App = () => {
  const [data, setData] = useState([]);

  // 初始化数据:直接使用导入的JSON文件
  useEffect(() => {
    setData([...carData]);
  }, []);

  // 处理品牌复选框点击事件
  const handleBrandCheck = (brandIndex) => {
    const updatedData = [...data];
    const newBrandStatus = !updatedData[brandIndex].status;
    updatedData[brandIndex].status = newBrandStatus;
    // 同步该品牌下所有车型的选中状态
    updatedData[brandIndex].children.forEach(child => {
      child.status = newBrandStatus;
    });
    setData(updatedData);
  };

  // 处理车型复选框点击事件
  const handleModelCheck = (brandIndex, modelIndex) => {
    const updatedData = [...data];
    // 切换当前车型的选中状态
    updatedData[brandIndex].children[modelIndex].status = !updatedData[brandIndex].children[modelIndex].status;
    
    // 检查该品牌下所有车型是否全选
    const allModelsChecked = updatedData[brandIndex].children.every(child => child.status);
    // 未全选则取消品牌复选框选中状态
    updatedData[brandIndex].status = allModelsChecked;
    
    setData(updatedData);
  };

  return (
    <div>
      <h1>Car Brands and its Models</h1>
      {data.map((brand, brandIndex) => (
        <div key={brandIndex} className="data">
          <table className="table">
            <tbody>
              <tr>
                <th>
                  <input
                    type="checkbox"
                    className="checkbox"
                    checked={brand.status}
                    onChange={() => handleBrandCheck(brandIndex)}
                  />
                  {brand.display} ({brand.count})
                </th>
              </tr>
              {/* 仅当品牌选中时显示子车型列表 */}
              {brand.status && (
                <tr>
                  <td>
                    <div className="datas">
                      {brand.children.map((model, modelIndex) => (
                        <div key={modelIndex} className="model-item">
                          <input
                            type="checkbox"
                            className="checkbox"
                            checked={model.status}
                            onChange={() => handleModelCheck(brandIndex, modelIndex)}
                          />
                          {model.display} ({model.count})
                        </div>
                      ))}
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
};

export default App;

关键逻辑说明

  • 独立状态管理:基于原始数据的status字段维护每个品牌和车型的选中状态,避免全局状态导致的跨品牌冲突
  • 品牌-车型联动:点击品牌复选框时,同步更新该品牌下所有车型的选中状态,并通过品牌status控制车型列表的显示/隐藏
  • 车型-品牌反向联动:点击车型后自动检查同品牌下所有车型的选中状态,若未全选则取消品牌复选框的选中状态
  • 修正数据初始化:删除原代码中错误的fetch调用,直接使用导入的JSON数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:15:58