### Start Development Server Source: https://github.com/react-component/tree/blob/master/README.md Start the development server to run the application. ```bash npm start ``` -------------------------------- ### Install Dependencies Source: https://github.com/react-component/tree/blob/master/README.md Install the necessary dependencies for the project. ```bash npm install ``` -------------------------------- ### Dropdown Example Source: https://github.com/react-component/tree/blob/master/docs/demo/dropdown.md A basic example of the Dropdown component. Ensure the component is imported before use. ```jsx import React from 'react'; import { Dropdown } from '@arco-design/web-react'; const options = [ { label: 'Option 1', value: '1' }, { label: 'Option 2', value: '2' }, { label: 'Option 3', value: '3' }, ]; const App = () => ( Dropdown Button ); export default App; ``` -------------------------------- ### onDragStart Event Example Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when dragging begins on a node. Use this to log the start of a drag operation. ```typescript { console.log('Started dragging:', info.node.title); }} /> ``` -------------------------------- ### Complete Tree Configuration Example Source: https://github.com/react-component/tree/blob/master/_autodocs/configuration.md This example demonstrates a full configuration of the Tree component, including data structure, selection, expansion, checkboxes, drag and drop, virtual scrolling, and styling options. It requires React and the '@rc-component/tree' library. ```typescript import Tree from '@rc-component/tree'; import type { DataNode } from '@rc-component/tree'; const treeData: DataNode[] = [ { title: 'Documents', key: 'docs', children: [ { title: 'README', key: 'docs-readme', isLeaf: true }, { title: 'API', key: 'docs-api', isLeaf: true }, ], }, ]; export function ConfiguredTree() { const [expandedKeys, setExpandedKeys] = React.useState(['docs']); const [selectedKeys, setSelectedKeys] = React.useState([]); const [checkedKeys, setCheckedKeys] = React.useState([]); return ( setSelectedKeys(keys)} // Expansion expandedKeys={expandedKeys} onExpand={(keys) => setExpandedKeys(keys)} expandAction="doubleClick" // Checkboxes checkable checkedKeys={checkedKeys} onCheck={(keys) => setCheckedKeys(keys)} // Drag and Drop draggable allowDrop={({ dropPosition }) => dropPosition === 0} // Virtual scrolling height={400} itemHeight={32} virtual // Styling showIcon showLine icon={} styles={{ itemIcon: { color: 'blue' } }} /> ); } ``` -------------------------------- ### Dynamic Data Loading Example Source: https://github.com/react-component/tree/blob/master/docs/demo/dynamic.md This example shows how to load data dynamically for tree nodes. Ensure the `loadData` function is correctly implemented to fetch and return child nodes when a parent node is expanded. ```jsx import React from 'react'; import { Tree } from 'antd'; const { TreeNode } = Tree; const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'leaf 1', key: '0-0-0', isLeaf: true }, { title: 'leaf 2', key: '0-0-1', isLeaf: true } ] }, { title: 'parent 2', key: '0-1' } ]; class Demo extends React.Component { onLoadData = treeNode => new Promise(resolve => { if (treeNode.props.children) { resolve(); return; } setTimeout(() => { this.setState( { treeData: this.state.treeData.map(node => { if (node.key === treeNode.props.eventKey) { return { ...node, children: [ { title: 'leaf 3', key: `${treeNode.props.eventKey}-0`, isLeaf: true }, { title: 'leaf 4', key: `${treeNode.props.eventKey}-1`, isLeaf: true } ] }; } return node; }) }, () => { resolve(); } ); }, 1000); }); state = { treeData }; renderTreeNodes = data => data.map(item => { if (item.children) { return ( {this.renderTreeNodes(item.children)} ); } return ; }); render() { return ( {this.renderTreeNodes(this.state.treeData)} ); } } export default Demo; ``` -------------------------------- ### Selectable Tree Example Source: https://github.com/react-component/tree/blob/master/docs/demo/selectable.md A basic example of a tree component with selectable nodes. Ensure the `selectable` prop is set to `true` to enable this feature. ```jsx import React from 'react'; import { Tree } from 'antd'; const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', children: [ { title: 'leaf 1-0-0', key: '0-0-0-0', }, { title: 'leaf 1-0-1', key: '0-0-0-1', }, ], }, { title: 'parent 1-1', key: '0-0-1', children: [ { title: 'leaf 1-1-0', key: '0-0-1-0', }, { title: 'leaf 1-1-1', key: '0-0-1-1', }, ], }, ], }, { title: 'parent 2', key: '0-1', children: [ { title: 'parent 2-0', key: '0-1-0', children: [ { title: 'leaf 2-0-0', key: '0-1-0-0', }, ], }, ], }, ]; const App = () => ; export default App; ``` -------------------------------- ### Custom Switch Icon Example Source: https://github.com/react-component/tree/blob/master/docs/demo/custom-switch-icon.md This React component demonstrates how to implement a custom switch icon for expanding and collapsing tree nodes. Ensure the necessary tree component library is installed and imported. ```jsx import React from 'react'; import { Tree } from 'antd'; const { TreeNode } = Tree; const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', children: [ { title: 'leaf 1-0-0', key: '0-0-0-0', }, { title: 'leaf 1-0-1', key: '0-0-0-1', }, ], }, { title: 'parent 1-1', key: '0-0-1', children: [ { title: 'leaf 1-1-0', key: '0-0-1-0', }, ], }, ], }, ]; const App = () => ( ( {isLeaf ? ( ) : expanded ? ( - ) : ( + )} )} /> ); export default App; ``` -------------------------------- ### Advanced Example: Theme-aware Drop Indicator Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/drop-indicator.md An advanced example showcasing a theme-aware custom drop indicator that considers UI theme properties like prefix class and direction. ```APIDOC ## Advanced Example: Theme-aware Drop Indicator ```typescript import Tree from '@rc-component/tree'; import type { DropIndicatorProps } from '@rc-component/tree'; interface ThemeDropIndicatorProps extends DropIndicatorProps { prefixCls: string; direction: 'ltr' | 'rtl' | undefined; } const themeDropIndicator = (props: any) => { const { dropPosition, dropLevelOffset, indent, prefixCls, direction } = props; const leftOffset = direction === 'rtl' ? dropLevelOffset * indent : -dropLevelOffset * indent; const style: React.CSSProperties = { pointerEvents: 'none', position: 'absolute', right: 0, height: 2, backgroundColor: '#1890ff', left: leftOffset, }; switch (dropPosition) { case -1: style.top = 0; break; case 1: style.bottom = 0; break; case 0: style.bottom = 0; style.left = indent; break; } return (
); }; export function ThemedTree() { return ( ); } ``` ``` -------------------------------- ### Custom Field Names Example Source: https://github.com/react-component/tree/blob/master/docs/demo/fieldNames.md This example shows how to use the `fieldNames` prop to specify custom names for the tree's data fields. Ensure your data matches the specified field names. ```tsx import React from 'react'; import { Tree } from '@alifd/next'; const data = [ { myId: '0-0', myTitle: 'Component A', myChildren: [ { myId: '0-0-0', myTitle: 'Component A-1', }, { myId: '0-0-1', myTitle: 'Component A-2', }, ], }, { myId: '0-1', myTitle: 'Component B', myDisabled: true, }, ]; const App = () => ( ); export default App; ``` -------------------------------- ### Basic Animation Example Source: https://github.com/react-component/tree/blob/master/docs/demo/animation.md This snippet shows a basic animation implementation. Ensure the necessary animation CSS classes or libraries are imported and configured. ```jsx import React from 'react'; import './animation.css'; // Assuming CSS for animation is in this file const AnimatedComponent = () => { return (
Hello, Animation!
); }; export default AnimatedComponent; ``` -------------------------------- ### Basic Tree Usage Example Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/tree.md Demonstrates how to use the Tree component with sample data, managing expanded, selected, and checked states using React hooks. ```typescript import Tree from '@rc-component/tree'; import type { DataNode } from '@rc-component/tree'; const treeData: DataNode[] = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leaf', key: '0-0-0-0' }, { title: 'leaf', key: '0-0-0-1' }, ], }, { title: 'parent 1-1', key: '0-0-1', children: [{ title: 'sss', key: '0-0-1-0' }], }, ], }, ]; export function MyTree() { const [expandedKeys, setExpandedKeys] = React.useState(['0-0']); const [selectedKeys, setSelectedKeys] = React.useState(['0-0-0']); const [checkedKeys, setCheckedKeys] = React.useState(['0-0-0']); const onExpand = (newExpandedKeys) => { setExpandedKeys(newExpandedKeys); }; const onSelect = (selectedKeys, info) => { setSelectedKeys(selectedKeys); }; const onCheck = (checkedKeys) => { setCheckedKeys(checkedKeys); }; return ( ); } ``` -------------------------------- ### Basic Context Menu Example Source: https://github.com/react-component/tree/blob/master/docs/demo/contextmenu.md This snippet shows a basic implementation of a context menu for tree nodes. It requires the React Tree component and a context menu handler. ```jsx import React from 'react'; import Tree from '@splunk/react-ui/Tree'; import Menu from '@splunk/react-ui/Menu'; import Button from '@splunk/react-ui/Button'; const Demo = () => { const [contextMenu, setContextMenu] = React.useState({ open: false, x: 0, y: 0, }); const handleContextMenu = (e, node) => { e.preventDefault(); setContextMenu({ open: true, x: e.clientX, y: e.clientY, }); console.log('Context menu opened for node:', node); }; const handleCloseContextMenu = () => { setContextMenu({ open: false, x: 0, y: 0, }); }; const handleMenuItemClick = (action, node) => { console.log(`Action '${action}' clicked for node:`, node); handleCloseContextMenu(); }; const renderNode = (node) => ( handleContextMenu(e, node)} > {node.children && node.children.map(renderNode)} ); const treeData = [ { id: '1', label: 'Root Node 1', children: [ { id: '1-1', label: 'Child Node 1.1' }, { id: '1-2', label: 'Child Node 1.2' }, ], }, { id: '2', label: 'Root Node 2', }, ]; return (
{treeData.map(renderNode)} handleMenuItemClick('edit', null)}>Edit handleMenuItemClick('delete', null)}>Delete handleMenuItemClick('copy', null)}>Copy
); }; export default Demo; ``` -------------------------------- ### Draggable Component Example Source: https://github.com/react-component/tree/blob/master/docs/demo/draggable.md This snippet shows a basic implementation of a draggable component in React. It requires the component to be set up with the necessary props for drag-and-drop behavior. ```jsx import React from 'react'; import { Tree } from '@arco-design/web-react'; const TreeNode = Tree.Node; const App = () => { const data = [ { key: '0-0', title: 'Trunk 1', children: [ { key: '0-0-0', title: 'Leaf 1.1', }, { key: '0-0-1', title: 'Leaf 1.2', }, ], }, { key: '0-1', title: 'Trunk 2', children: [ { key: '0-1-0', title: 'Leaf 2.1', }, ], }, ]; const onDrop = (e) => { console.log('Dropped:', e); }; return ( {node.title}} /> ); }; export default App; ``` -------------------------------- ### Implement Drag and Drop with Auto-Expand Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md This example enables auto-expansion of nodes when a draggable item is being dragged over them. It uses the onDragEnter event to manage the expanded keys state. ```typescript export function AutoExpandDragTree() { const [expandedKeys, setExpandedKeys] = React.useState([]); const onDragEnter = (info: any) => { // Auto-expand node when dragging over it setExpandedKeys(prev => { if (!prev.includes(info.node.key)) { return [...prev, info.node.key]; } return prev; }); }; return ( ); } ``` -------------------------------- ### Basic Controlled Tree Source: https://github.com/react-component/tree/blob/master/docs/demo/basic-controlled.md This example shows a controlled tree component where the expanded state is managed externally. It requires React and the tree component library. ```jsx import React, { useState } from 'react'; import { Tree } from 'react-tree-graph'; const data = { name: 'root', children: [ { name: 'parent1', children: [ { name: 'child1.1' }, { name: 'child1.2' } ] }, { name: 'parent2', children: [ { name: 'child2.1' }, { name: 'child2.2' } ] } ] }; const BasicControlled = () => { const [expandedNodes, setExpandedNodes] = useState(['root', 'parent1']); const handleExpand = (nodeIds) => { setExpandedNodes(nodeIds); }; return ( ); }; export default BasicControlled; ``` -------------------------------- ### Entity Structure Example Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/context-and-internals.md Illustrates the structure of an entity object created by `convertDataToEntities`. Each entity contains node data, its position in the tree, and links to its children. ```typescript { '1': { key: '1', level: 0, index: 0, pos: '0-0', node: {...data...}, nodes: [{...data...}], children: [{...child entities...}] } } ``` -------------------------------- ### onDrop Event Type and Example Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when a node is dropped on another node. Provides details about the drag operation, including the dragged node, target node, and drop position. The example shows how to determine if the drop was inside or between nodes. ```typescript onDrop?: (info: NodeDragEventParams & { dragNode: EventDataNode; dragNodesKeys: Key[]; dropPosition: number; dropToGap: boolean; }) => void { const dragNode = info.dragNode; const targetNode = info.node; if (info.dropPosition === 0) { // Drop inside target console.log(`Dropped ${dragNode.title} into ${targetNode.title}`); } else { // Drop above/below console.log(`Dropped ${dragNode.title} ${info.dropPosition > 0 ? 'after' : 'before'} ${targetNode.title}`); } }} /> ``` -------------------------------- ### Async Loading Example Source: https://github.com/react-component/tree/blob/master/_autodocs/REFERENCE.md Implement this pattern to load child nodes on demand. The `loadData` prop accepts a function that fetches and returns children, with an optional `onLoad` callback for post-load actions. ```typescript { return fetch(`/api/children/${node.key}`) .then(r => r.json()) .then(children => { // Return resolved children }); }} onLoad={(loadedKeys) => { console.log('Loaded:', loadedKeys); }} /> ``` -------------------------------- ### Unit Test Tree Component Rendering Source: https://github.com/react-component/tree/blob/master/_autodocs/REFERENCE.md Use React Testing Library to render the Tree component and assert its presence in the document. This is a basic example for unit testing. ```typescript import { render, screen } from '@testing-library/react'; import Tree from '@rc-component/tree'; const treeData = [ { title: 'Node 1', key: '1' } ]; render(); expect(screen.getByText('Node 1')).toBeInTheDocument(); ``` -------------------------------- ### Implement Simple Drag and Drop Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md This example shows a basic implementation of drag and drop functionality for the tree component. It includes a placeholder for custom drag-drop logic and a restriction to prevent dropping inside leaf nodes. ```typescript export function DragDropTree() { const [treeData, setTreeData] = React.useState(initialData); const onDrop = (info: any) => { // Implement your drag-drop logic if (info.node.isLeaf) { return; // Can't drop inside leaf nodes } // Update tree structure... }; return ( ); } ``` -------------------------------- ### Theme-aware Custom Drop Indicator Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/drop-indicator.md An advanced example demonstrating a theme-aware custom drop indicator that considers RTL direction and uses CSS classes. ```typescript import Tree from '@rc-component/tree'; import type { DropIndicatorProps } from '@rc-component/tree'; interface ThemeDropIndicatorProps extends DropIndicatorProps { prefixCls: string; direction: 'ltr' | 'rtl' | undefined; } const themeDropIndicator = (props: any) => { const { dropPosition, dropLevelOffset, indent, prefixCls, direction } = props; const leftOffset = direction === 'rtl' ? dropLevelOffset * indent : -dropLevelOffset * indent; const style: React.CSSProperties = { pointerEvents: 'none', position: 'absolute', right: 0, height: 2, backgroundColor: '#1890ff', left: leftOffset, }; switch (dropPosition) { case -1: style.top = 0; break; case 1: style.bottom = 0; break; case 0: style.bottom = 0; style.left = indent; break; } return (
); }; export function ThemedTree() { return ( ); } ``` -------------------------------- ### Custom Drop Indicator Implementation Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/drop-indicator.md Provides an example of a custom drop indicator component using the `dropIndicatorRender` prop on the Tree component. ```typescript import Tree from '@rc-component/tree'; const customDropIndicator = (props: DropIndicatorProps) => { const { dropPosition, dropLevelOffset, indent } = props; const getPositionText = () => { switch (dropPosition) { case -1: return '⬆ Above'; case 0: return '→ Inside'; case 1: return '⬇ Below'; default: return ''; } }; return (
{getPositionText()}
); }; export function MyTree() { return ( ); } ``` -------------------------------- ### Custom Tree Data Example with FieldDataNode Source: https://github.com/react-component/tree/blob/master/_autodocs/types.md Demonstrates how to define and use a custom tree node type with a specific children field name ('childNodes') using FieldDataNode. ```typescript interface CustomNodeData { id: number; label: string; } type CustomTreeNode = FieldDataNode; const treeData: CustomTreeNode[] = [ { id: 1, label: 'Node 1', childNodes: [ { id: 2, label: 'Node 1.1', childNodes: [] }, ], }, ]; ``` -------------------------------- ### Draggable and Droppable Tree Example Source: https://github.com/react-component/tree/blob/master/docs/demo/draggable-allow-drop.md This snippet shows a complete React component for a draggable and droppable tree. It requires a JSX file containing the component logic and structure. ```jsx import React, { useState, useCallback } from 'react'; import { Tree, TreeNode, useTree } from '@min-fe/react-tree'; const initialData = [ { key: '0', label: 'parent 1', children: [ { key: '0-0', label: 'child 1', }, { key: '0-1', label: 'child 2', children: [ { key: '0-1-0', label: 'grandchild 1', }, ], }, ], }, { key: '1', label: 'parent 2', }, ]; const App = () => { const [data, setData] = useState(initialData); const { drag, drop, getTreeProps, getNodeProps, getDragProps, getDropProps } = useTree({ data, onChange: setData, // You can customize drag and drop behavior here // For example, to only allow dropping on specific nodes or to customize drop indicators // dragConfig: { // canDrag: (node) => node.key !== '0-1-0', // Example: disable dragging grandchild // }, // dropConfig: { // canDrop: (dropNode, dragNode) => dropNode.key !== '0-0', // Example: disable dropping on child 1 // }, }); const renderNode = useCallback( (node) => (
{node.label}
), [getNodeProps, getDragProps] ); return ( {data.map((node) => ( ))} ); }; export default App; ``` -------------------------------- ### Big Data Example Source: https://github.com/react-component/tree/blob/master/docs/demo/big-data.md This snippet shows a React component for handling big data visualization using the Tree component. It's designed for scenarios with a large number of nodes. ```jsx import React from 'react'; import Tree from '@components/tree'; const App = () => { const data = [ { key: '0', title: 'parent 1', children: [ { key: '0-0', title: 'leaf 1', }, { key: '0-1', title: 'leaf 2', }, ], }, { key: '1', title: 'parent 2', children: [ { key: '1-0', title: 'leaf 3', isLeaf: true, }, ], }, ]; return (

Big Data Tree Example

); }; export default App; ``` -------------------------------- ### Tree Controlled Mode Selection Example Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Demonstrates using the Tree component in controlled mode, where the parent component manages the selected keys state. The selectedKeys state is updated via the onSelect handler. ```jsx const [selectedKeys, setSelectedKeys] = React.useState([]); setSelectedKeys(keys)} /> ``` -------------------------------- ### Uncontrolled Tree Example Source: https://github.com/react-component/tree/blob/master/_autodocs/REFERENCE.md Use this pattern when the tree component should manage its own state internally. Basic configuration includes prefix, data, and enabling selection and checking. ```typescript ``` -------------------------------- ### Tree Integration with Redux Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md Integrate the tree component with Redux for global state management. This example shows how to connect the tree's expanded and selected states to a Redux store, dispatching actions to update them. ```typescript import { useSelector, useDispatch } from 'react-redux'; export function ReduxTree() { const dispatch = useDispatch(); const { expandedKeys, selectedKeys } = useSelector(state => state.tree); return ( dispatch(setExpandedKeys(keys))} onSelect={(keys) => dispatch(setSelectedKeys(keys))} /> ); } ``` -------------------------------- ### Tree Preventing Operations Example Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Demonstrates how to prevent certain operations, such as selecting more than a maximum number of nodes. The onSelect handler checks the number of selected keys before updating the state. ```jsx { // Only allow selecting 3 nodes max if (keys.length <= 3) { setSelectedKeys(keys); } }} /> ``` -------------------------------- ### Tree Uncontrolled Mode Selection Example Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Demonstrates using the Tree component in uncontrolled mode, where the component manages its own state. The onSelect handler is used to log selected keys without needing to update external state. ```jsx { console.log('Selected:', keys); // No need to update state yourself }} /> ``` -------------------------------- ### Tree Filtering Selection Example Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Shows how to filter selection in the Tree component to only allow selecting leaf nodes. The onSelect handler checks if the selected node has children before updating the state. ```jsx { // Only select leaf nodes if (!info.node.children || info.node.children.length === 0) { setSelectedKeys(keys); } }} /> ``` -------------------------------- ### Implement Checkbox with Parent Independence (Strict Mode) Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md This example demonstrates the `checkStrictly` mode for checkboxes, where parent and child nodes can be checked independently. It manages both checked and half-checked states. ```typescript export function StrictCheckTree() { const [checkedState, setCheckedState] = React.useState({ checked: [] as React.Key[], halfChecked: [] as React.Key[], }); return ( { if (typeof keys === 'object' && 'checked' in keys) { setCheckedState(keys); } }} /> ); } ``` -------------------------------- ### Controlled Tree Example Source: https://github.com/react-component/tree/blob/master/_autodocs/REFERENCE.md Use this pattern when the parent component needs to manage the tree's state (expanded and selected keys). State is managed using React's useState hook and passed via props. ```typescript const [expandedKeys, setExpandedKeys] = useState([]); const [selectedKeys, setSelectedKeys] = useState([]); setSelectedKeys(keys)} /> ``` -------------------------------- ### Get All Checked Leaf Nodes Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md This snippet shows how to retrieve only the checked leaf nodes from a tree with checkboxes enabled. It includes a helper function to filter nodes and an example button to trigger the export. ```typescript export function CheckableWithLeafExport() { const [checkedKeys, setCheckedKeys] = React.useState([]); const getCheckedLeaves = () => { return checkedKeys.filter(key => { const node = findNodeByKey(treeData, key); return !node.children || node.children.length === 0; }); }; const handleExport = () => { const leaves = getCheckedLeaves(); console.log('Checked leaf nodes:', leaves); }; return ( <> { setCheckedKeys(Array.isArray(keys) ? keys : keys.checked); }} /> ); } ``` -------------------------------- ### Get Tree Node Properties Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/context-and-internals.md Extracts TreeNode properties from a TreeData object, correctly handling field name mappings. ```typescript export function getTreeNodeProps(key: Key, options: any): TreeNodeProps ``` -------------------------------- ### onDragStart Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when the dragging of a node begins. ```APIDOC ## onDragStart ### Description Fired when dragging begins on a node. ### Method ```typescript onDragStart?: (info: NodeDragEventParams) => void ``` ### Parameters `info`: An object containing drag event details. - `event`: React's native drag event. - `node`: The node data that is being dragged. ### Example ```typescript { console.log('Started dragging:', info.node.title); }} /> ``` ``` -------------------------------- ### onFocus Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when the tree container gains focus. ```APIDOC ## onFocus ### Description Fired when tree container receives focus. ### Type ```typescript onFocus?: React.FocusEventHandler ``` ``` -------------------------------- ### onContextMenu Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when the context menu is triggered by a right-click on the tree container. ```APIDOC ## onContextMenu ### Description Fired on right-click on the tree container. ### Type ```typescript onContextMenu?: React.MouseEventHandler ``` ``` -------------------------------- ### onKeyDown Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when a key is pressed while the tree container has focus. ```APIDOC ## onKeyDown ### Description Fired on keyboard input while tree is focused. ### Type ```typescript onKeyDown?: React.KeyboardEventHandler ``` ``` -------------------------------- ### CSS Customization for Drop Indicator Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/drop-indicator.md Override the default red drop indicator's appearance using CSS. This example changes the color to blue and increases the thickness. ```css .rc-tree-drop-indicator { background-color: #1890ff; /* Change to blue */ height: 3px; /* Make thicker */ } ``` -------------------------------- ### Import Tree Component LESS Source: https://github.com/react-component/tree/blob/master/_autodocs/REFERENCE.md Import the LESS version of the Tree component styles. Ensure you have a LESS preprocessor configured. ```less @import '@rc-component/tree/assets/index.less'; ``` -------------------------------- ### onClick Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when any node is clicked, before selection or checking logic is applied. This is a general click event handler. ```APIDOC ## onClick ### Description Fired when any node in the tree is clicked. This event is triggered before any selection or checking logic is processed, allowing for custom click handling. ### Method Callback Function ### Parameters - **(NodeMouseEventHandler)** - The handler function for the click event. ### Source `src/Tree.tsx:129` ``` -------------------------------- ### onLoad Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when a node finishes loading its children asynchronously. It provides the keys of loaded nodes and information about the node that completed loading. ```APIDOC ## onLoad ### Description Fired after a node has finished loading its children asynchronously. Useful for tracking loading progress and confirming data availability. ### Method Callback Function ### Parameters - **loadedKeys** (Key[]) - Required - Array of all node keys that have been loaded. - **info** (object) - Required - Additional information about the load event. - **info.event** ('load') - The event type, always 'load'. - **info.node** (EventDataNode) - The node that finished loading. ### Request Example ```typescript { return fetch(`/api/children/${node.key}`) .then(r => r.json()) .then(children => { // Return children }); }} onLoad={(loadedKeys, info) => { console.log(`Loaded node: ${info.node.key}`); console.log('All loaded:', loadedKeys); }} /> ``` ``` -------------------------------- ### Get Expand Range for Animation Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/context-and-internals.md Calculates the range of nodes that become newly visible between two expand states. This is used to drive animation effects when expanding or collapsing nodes. ```typescript export function getExpandRange( shorter: FlattenNode[], longer: FlattenNode[], key: Key ): FlattenNode[] ``` -------------------------------- ### Modern Recommended Usage with treeData Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/tree-node.md Illustrates the current recommended approach for defining tree structures using the `treeData` prop on the Tree component. This method is more efficient and preferred for new development. ```typescript import Tree from '@rc-component/tree'; import type { DataNode } from '@rc-component/tree'; const treeData: DataNode[] = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leaf', key: '0-0-0-0' }, { title: 'leaf', key: '0-0-0-1' }, ], }, { title: 'parent 1-1', key: '0-0-1', children: [ { title: 'leaf', key: '0-0-1-0' }, ], }, ], }, ]; export function ModernTree() { return ; } ``` -------------------------------- ### Custom Drop Indicator Implementation Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/drop-indicator.md Demonstrates how to implement a custom drop indicator by providing a `dropIndicatorRender` function to the Tree component. ```APIDOC ## Custom Drop Indicator To use a custom drop indicator, pass `dropIndicatorRender` to Tree: ```typescript import Tree from '@rc-component/tree'; const customDropIndicator = (props: DropIndicatorProps) => { const { dropPosition, dropLevelOffset, indent } = props; const getPositionText = () => { switch (dropPosition) { case -1: return '⬆ Above'; case 0: return '→ Inside'; case 1: return '⬇ Below'; default: return ''; } }; return (
{getPositionText()}
); }; export function MyTree() { return ( ); } ``` ``` -------------------------------- ### Get Drag Children Keys Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/utility-functions.md Retrieves all descendant node keys for a given parent node key. Primarily used in drag-and-drop operations to identify nodes that should be moved together. ```typescript import { getDragChildrenKeys } from '@rc-component/tree'; // Tree structure: // - 1 // - 1-1 // - 1-1-1 // - 1-2 const childKeys = getDragChildrenKeys('1', keyEntities); console.log(childKeys); // ['1-1', '1-1-1', '1-2'] ``` -------------------------------- ### Custom Drop Indicator Render Function Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/drop-indicator.md Use CSS-in-JS within the Tree's styles prop to create a custom drop indicator. This example renders a green indicator with adjustable positioning. ```typescript (
)} /> ``` -------------------------------- ### onRightClick Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when a node is right-clicked, typically to trigger a context menu. Provides event and node information. ```APIDOC ## onRightClick ### Description Fired when a node is right-clicked. Commonly used to display a context menu for the clicked node. ### Method Callback Function ### Parameters - **info** (object) - Required - Information about the right-click event. - **info.event** (React.MouseEvent) - The React mouse event. - **info.node** (EventDataNode) - The node that was right-clicked. ### Example ```typescript { console.log('Right-clicked:', info.node.title); // Show context menu }} /> ``` ``` -------------------------------- ### Controlled Checkbox State with Strict Checking Source: https://github.com/react-component/tree/blob/master/_autodocs/configuration.md Configure checkboxes for the Tree component with strict parent-child independence. This example shows how to manage checked and partially checked states using the `checkedKeys` prop. ```typescript { // checkedKeys is { checked: [...], halfChecked: [...] } }} /> ``` -------------------------------- ### onExpand Source: https://github.com/react-component/tree/blob/master/_autodocs/events.md Fired when a node is expanded or collapsed. It returns the expanded keys and information about the node and its expanded state. ```APIDOC ## onExpand ### Description Fired when a node's expansion state changes (expanded or collapsed). Provides the list of currently expanded keys and details about the node and state change. ### Method Callback Function ### Parameters - **expandedKeys** (Key[]) - Required - Array of all currently expanded node keys. - **info** (object) - Required - Additional information about the expansion event. - **info.node** (EventDataNode) - The node that was expanded or collapsed. - **info.expanded** (boolean) - True if the node was expanded, false if collapsed. - **info.nativeEvent** (MouseEvent) - The native DOM MouseEvent. ### Request Example ```typescript { console.log('Expanded keys:', expandedKeys); console.log('Node expanded:', info.expanded); }} /> ``` ``` -------------------------------- ### Get Tree Entity by Key Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/context-and-internals.md Looks up a tree entity by its key within a map of key entities. This provides a type-safe way to access entity data, including parent and children information. ```typescript import getEntity from './utils/keyUtil'; const entity = getEntity(keyEntities, '1-0-1'); console.log(entity.parent.key); // Parent key console.log(entity.children.length); // Number of children ``` -------------------------------- ### Implement Multi-Selection with a Limit Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md Enables multi-selection with a maximum limit on the number of selectable nodes. A warning is logged if the limit is exceeded. ```typescript export function LimitedMultiSelectTree() { const [selectedKeys, setSelectedKeys] = React.useState([]); const MAX_SELECTED = 5; return ( { if (keys.length <= MAX_SELECTED) { setSelectedKeys(keys); } else { // Show warning console.warn(`Maximum ${MAX_SELECTED} nodes can be selected`); } }} /> ); } ``` -------------------------------- ### Implement Single Selection with Default Source: https://github.com/react-component/tree/blob/master/_autodocs/patterns-and-recipes.md Configures the tree for single selection, pre-selecting a default key. The `onSelect` handler ensures only one node can be selected at a time. ```typescript export function SingleSelectTree() { const [selectedKeys, setSelectedKeys] = React.useState(['1']); return ( { // Only allow one selection setSelectedKeys(info.selected ? [info.node.key] : []); }} /> ); } ``` -------------------------------- ### Import TreeNode Component Source: https://github.com/react-component/tree/blob/master/_autodocs/api-reference/tree-node.md Import the TreeNode component and its associated types from the library. This is the first step when using the component. ```typescript import { TreeNode } from '@rc-component/tree'; import type { TreeNodeProps } from '@rc-component/tree'; ```