首页 > 解决方案 > 我想在反应 js 中创建检查嵌套数据的复选框

问题描述

我的数据在嵌套数组对象中。我想像树视图一样选中/取消选中节点。IE。when any child node is selected then the parent node is checked itself. 这就是我的嵌套数组的样子。

这是我的嵌套 JSON。从这个对象,我从这个数据创建一个树视图:

我的树结构

 const nodes = [
  {
    value: "/app",
    label: "app",
    children: [
      {
        value: "/app/Http",
        label: "Http",
        children: [
          {
            value: "/app/Http/Controllers",
            label: "Controllers",
            children: [
              {
                value: "/app/Http/Controllers/WelcomeController.js",
                label: "WelcomeController.js",
              },
            ],
          },
          {
            value: "/app/Http/routes.js",
            label: "routes.js",
          },
        ],
      },
      {
        value: "/app/Providers",
        label: "Providers",
        children: [
          {
            value: "/app/Http/Providers/EventServiceProvider.js",
            label: "EventServiceProvider.js",
          },
        ],
      },
    ],
  },
  {
    value: "/config",
    label: "config",
    children: [
      {
        value: "/config/app.js",
        label: "app.js",
      },
      {
        value: "/config/database.js",
        label: "database.js",
      },
    ],
  },
  {
    value: "/public",
    label: "public",
    children: [
      {
        value: "/public/assets/",
        label: "assets",
        children: [
          {
            value: "/public/assets/style.css",
            label: "style.css",
          },
        ],
      },
      {
        value: "/public/index.html",
        label: "index.html",
      },
    ],
  },
  {
    value: "/.env",
    label: ".env",
  },
  {
    value: "/.gitignore",
    label: ".gitignore",
  },
  {
    value: "/README.md",
    label: "README.md",
  },
];

我正在使用此功能在检查孩子时检查父母。

checkChange(targetNode: any, event) {
    /// debugger;
    const targetNodeId = targetNode.id;
    this.findIndexNestedforCheckbox(targetNode, targetNodeId);
    let newTableData = [...this.state.tableData];
    this.setState({ tableData: newTableData, isActionFooter: true });
  }
findIndexNestedforCheckbox(data, index) {
   
    if (data.id === index) data.isChecked = "Yes";

    let result;
    const i = (data.children || []).findIndex((child) => {
      child.isChecked = "Yes";

      return (result = this.findIndexNestedforCheckbox(child, index));
    });
    if (result) return [i, ...result];
  }

标签: reactjsbabeljs

解决方案


推荐阅读