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

时间:2018-04-22 07:06:26

标签: reactjs d3.js

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

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

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

这就是我的预期(根据D3 DocumentationExpected 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. 如何获得折叠/展开功能?
  3. 请告诉我我做错了什么。谢谢你的时间。 (:

1 个答案:

答案 0 :(得分:0)

我终于得到了答案。

我需要将样式指定为<path>标记,如下所示。

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