【antd受控树Tree组件】

1、效果

【antd受控树Tree组件】_第1张图片

2、代码

import React, { useState } from "react";
import "./index.css";
import { Tree } from "antd";
import type { DataNode } from "antd/es/tree";

const treeData: DataNode[] = [
  {
    title: "0-0",
    key: "0-0",
    children: [
      {
        title: "0-0-0",
        key: "0-0-0",
        children: [
          {
            title: "0-0-0-0",
            key: "0-0-0-0",
            children: [
              { title: "0-0-0-0-1", key: "00--0-0-1" },
              { title: "0-0-0-0-2", key: "0-0-0-0-2" },
            ],
          },
          { title: "0-0-0-1", key: "0-0-0-1" },
          { title: "0-0-0-2", key: "0-0-0-2" },
        ],
      },
      {
        title: "0-0-1",
        key: "0-0-1",
        children: [
          { title: "0-0-1-0", key: "0-0-1-0" },
          { title: "0-0-1-1", key: "0-0-1-1" },
          { title: "0-0-1-2", key: "0-0-1-2" },
        ],
      },
      {
        title: "0-0-2",
        key: "0-0-2",
      },
    ],
  },
  {
    title: "0-1",
    key: "0-1",
    children: [
      { title: "0-1-0-0", key: "0-1-0-0" },
      { title: "0-1-0-1", key: "0-1-0-1" },
      { title: "0-1-0-2", key: "0-1-0-2" },
    ],
  },
  {
    title: "0-2",
    key: "0-2",
  },
];

const App: React.FC = () => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  const onExpand = (expandedKeysValue: React.Key[], { node: { key } }) => {
    setExpandedKeys(expandedKeysValue);
    // 展开时,选中当前选项
    setSelectedKeys([key]);
  };

  // 选中与取消选中时,自动展开或收起当前折叠项
  const onSelect = (selectedKeysValue: React.Key[], { node: { key } }) => {
    setExpandedKeys((prevKeys) => {
      const newArr = new Set(expandedKeys);
      if (newArr.has(key)) {
        // 如果展开项已经有的话,就删掉
        newArr.delete(key);
      } else {
        // 没有的话,就加上
        newArr.add(key);
      }
      return [...newArr];
    });
    // 这里这样设置的话,就是点击谁,就一直选中谁
    setSelectedKeys([key]);
    // 这样设置的话,就是点击后,再次点击,会有取消选中的效果
    // setSelectedKeys(selectedKeysValue)
  };

  return (
    <Tree
      onExpand={onExpand}
      expandedKeys={expandedKeys}
      onSelect={onSelect}
      selectedKeys={selectedKeys}
      treeData={treeData}
    />
  );
};

export default App;

你可能感兴趣的:(前端,javascript,react.js)