import { NodeDataType, OrgChartComponentProps } from '../interface'; import classNames from 'classnames'; import React from 'react'; const DefaultOrgChart = (props: OrgChartComponentProps) => { const { data, expandAll = true, expandable = false, renderNode: customRenderNode, onExpand, onClick, } = props; const [expanded, setExpanded] = React.useState(false); const childrenLength = data.children?.length || 0; const colSpan: number = childrenLength * 2; /** * 渲染节点 * @param data * @returns */ const renderNode = (data: NodeDataType): React.ReactNode => { const contentNode: React.ReactNode = (
{data.label}
); return (
onClick && onClick(data)} > {!!customRenderNode ? customRenderNode(data, contentNode) : contentNode}
); }; /** * 处理展开 */ const handleExpandChange = () => { const newExpanded = !expanded; setExpanded(newExpanded); onExpand && onExpand(newExpanded, data); }; /** * 渲染垂直线 * @returns */ const renderVerticalLine = (): React.ReactNode => { return (
{expandable ? (
handleExpandChange()} >
) : null} ); }; /** * 渲染连接线 * @returns */ const renderConnectLines = (): React.ReactNode[] => { const lines: React.ReactNode[] = []; for (let index = 0; index < colSpan; index++) { lines.push(   , ); } return lines; }; /** * 渲染子节点 * @param datas * @returns */ const renderChildren = (datas: NodeDataType[] = []): React.ReactNode => { if (datas.length > 0) { return ( <> {renderVerticalLine()} {renderConnectLines()} {datas.map((data) => { return ( ); })} ); } return; }; React.useEffect(() => { setExpanded(expandAll); }, [expandAll]); return ( {renderNode(data)} {renderChildren(data.children)}
); }; export default DefaultOrgChart;