Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can create a function to handle the selection of the parent node in the tree. In this function, you can set the state to only select the parent node by checking if the clicked node has any children. If the clicked node is a parent node, you can set the state to select it and deselect any previously selected child node. Here is an example code snippet:

import { Tree } from 'antd';

const { TreeNode } = Tree;

class MyTree extends React.Component {
  state = {
    selectedKeys: [],
  };

  onSelect = (selectedKeys, { selected, node }) => {
    if (!node.children) {
      // Current node is a leaf node, do nothing
      return;
    }

    if (selected) {
      // Node is selected, update the state
      this.setState({ selectedKeys: [node.key] });
    } else {
      // Node is deselected
      this.setState({ selectedKeys: [] });
    }
  };

  render() {
    return (
      <Tree
        selectedKeys={this.state.selectedKeys}
        onSelect={this.onSelect}
      >
        <TreeNode key="parent" title="Parent Node">
          <TreeNode key="child1" title="Child Node 1" />
          <TreeNode key="child2" title="Child Node 2" />
        </TreeNode>
      </Tree>
    );
  }
}

In the onSelect function, we check if the clicked node has any children by checking the node.children property. If it doesn't have any children, we do nothing and the selectedKeys state is not updated. If the clicked node is a parent node, we update the state to only select that node and deselect any previously selected child node by setting selectedKeys to an array with only the parent node key. If the node is deselected, we simply set selectedKeys to an empty array.