gpt4 book ai didi

reactjs - 使用 D3 在 ReactJS 中没有获得具有预期链接样式的树

转载 作者:行者123 更新时间:2023-12-05 05:16:53 27 4
gpt4 key购买 nike

我是 D3.js 库的新手。我一直在尝试在 React JS 项目中实现它。

我只是使用 d3 函数进行计算,渲染部分将由 React JS 完成。

我成功地创建了一棵树,但我得到的链接的风格很奇怪(不符合预期)

这是我所期望的(根据 D3 Documentation ) Expected Result

但是我得到了下面的树:( enter image description here

我也无法折叠或展开...

您可以在下面找到代码。

componentDidMount() {
const width = 800, height = 800;

const tree = d3.tree().size([height, width - 160]);
const stratify = d3.stratify().id((d) => {
return d.name;
}).parentId((d) => {
return d.parent;
});
const root = stratify(this.state.data)
.sort((a, b) => {
return (a.height - b.height) || a.id.localeCompare(b.id);
});

this.setState({ paths: tree(root).links() });
this.setState({ nodes: root.descendants() })
}

render() {
let paths = this.state.paths && this.state.paths.map(item => {
let d = d3
.linkHorizontal()
.x((d) => {
return d.y;
})
.y((d) => {
return d.x;
});
return <path className='link' d={d(item)} />
})
let nodes = this.state.nodes && this.state.nodes.map((node, i) => {
return <g key={node.id} className={"node" + node.children ? " node--internal" : " node--leaf"}
transform={`translate(${node.y}, ${node.x})`}>
<circle r="10" style={{ 'fill': node.children ? 'lightsteelblue' : 'black' }} />
<text y="0" dy="0" textAnchor="middle"
style={{ 'fillOpacity': 1 }}>{node.name}</text>
</g>
})
return (
<svg className="tree-chart-basic" ref={(r) => this.chartRf = r} style={{ width: '800px', height: '800px' }}>
<g transform='translate(20,20)'>
{nodes}
{paths}
</g>
</svg>
);
}

this.state.data 将拥有如下数组

    [
{ "name": "ProjectA", "parent": "" },
{ "name": "ApplicationA", "parent": "ProjectA" },
{ "name": "EnvironmentB", "parent": "ProjectA" },

{ "name": "TierC", "parent": "ApplicationA" },
{ "name": "TierD", "parent": "ApplicationA" },
{ "name": "TierE", "parent": "ApplicationA" },

{ "name": "ServiceF", "parent": "EnvironmentB" },

{ "name": "ContainerG", "parent": "EnvironmentB" },
{ "name": "ContainerH", "parent": "TierE" },
{ "name": "ContainerH", "parent": "TierE" },
{ "name": "ContainerH", "parent": "TierE" },
{ "name": "ContainerH", "parent": "TierE" },
{ "name": "ContainerH", "parent": "TierE" },
{ "name": "ContainerH", "parent": "TierE" }
]
  1. 如何在我的代码中获得预期的树?
  2. 如何获得折叠/展开功能?

请告诉我我做错了什么。谢谢你的时间。 (:

最佳答案

我终于找到了答案。

我需要指定样式到<path>标记如下。

<path
fill="none"
stroke="#97a6ff"
strokeWidth="2px"
/>

关于reactjs - 使用 D3 在 ReactJS 中没有获得具有预期链接样式的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com