在我的 React 应用程序中,我一直在使用 d3 org 图表库来显示我的一些图表。
我使用的例子来自这里:
https://codesandbox.io/s/org-chart-fnx0zi?file=/src/components/orgChart.js
This is the component code:
import React, { useState, useRef, useLayoutEffect } from "react";
import ReactDOMServer from "react-dom/server";
import { OrgChart } from "d3-org-chart";
import CustomNodeContent from "./customNodeContent";
import CustomExpandButton from "./customExpandButton";
import EmployeeDetailsCard from "./employeeDetailsCard";
const styles = {
orgChart: {
height: "calc(100vh - 60px)",
backgroundColor: "#eaeaea",
},
};
const OrganizationalChart = (props) => {
const d3Container = useRef(null);
const [cardShow, setCardShow] = useState(false);
const [employeeId, setEmployeeId] = useState("");
const handleShow = () => setCardShow(true);
const handleClose = () => setCardShow(false);
useLayoutEffect(() => {
const toggleDetailsCard = (nodeId) => {
handleShow();
setEmployeeId(nodeId);
};
const chart = new OrgChart();
if (props.data && d3Container.current) {
chart
.container(d3Container.current)
.data(props.data)
.nodeWidth((d) => 300)
.nodeHeight((d) => 150)
.compactMarginBetween((d) => 80)
.onNodeClick((d) => {
toggleDetailsCard(d);
})
.buttonContent((node, state) => {
return ReactDOMServer.renderToStaticMarkup(
<CustomExpandButton {...node.node} />
);
})
.nodeContent((d) => {
return ReactDOMServer.renderToStaticMarkup(
<CustomNodeContent {...d} />
);
})
.render();
}
}, [props, props.data]);
return (
<div style={styles.orgChart} ref={d3Container}>
{cardShow && (
<EmployeeDetailsCard
employees={props.data}
employee={props.data.find((employee) => employee.id === employeeId)}
handleClose={handleClose}
/>
)}
</div>
);
};
export default OrganizationalChart;
它工作正常,但我不喜欢它自动重新排列节点的方式;例如,当我将子节点添加到根节点时,它最初是这样排列它们的:
然后在进一步扩展时重新排列。
如果它在一行中显示所有同级节点,我会更喜欢它,有什么办法可以做到这一点吗?
组织结构图的初始视图将为垂直视图。您可以通过添加
.compact(false)
来调整此值。通过这个你可以查看你的图表内联。