@10pearls/react-d3-tree 中文文档教程

发布于 3年前 浏览 29 项目主页 更新于 3年前

React D3 Tree

Greenkeeper 徽章构建状态覆盖状态Codacy 徽章npm 版本npm

React D3 Tree 是一个 React 组件,可让您表示分层数据(例如祖先树、组织结构、包依赖)作为动画 & 利用 D3tree 布局的交互式树图。

Contents

Demo

  • Current release: https://bkrem.github.io/react-d3-tree-demo/

Installation

yarn add react-d3-tree
# or
npm i --save react-d3-tree

Usage

import React from 'react';
import Tree from 'react-d3-tree';

const myTreeData = [
  {
    name: 'Top Level',
    attributes: {
      keyA: 'val A',
      keyB: 'val B',
      keyC: 'val C',
    },
    children: [
      {
        name: 'Level 2: A',
        attributes: {
          keyA: 'val A',
          keyB: 'val B',
          keyC: 'val C',
        },
      },
      {
        name: 'Level 2: B',
      },
    ],
  },
];

class MyComponent extends React.Component {
  render() {
    return (
 &nbsp; &nbsp; &nbsp;{/* <Tree /> will fill width/height of its container; in this case `#treeWrapper` */}
      <div id="treeWrapper" style={{width: '50em', height: '20em'}}>

        <Tree data={myTreeData} />

      </div>
    );
  }
}

Props

PropertyTypeOptionsRequired?DefaultDescription
dataarrayrequiredundefinedSingle-element array containing hierarchical object (see myTreeData above).
Contains (at least) name and parent keys.
nodeSvgShapeobjectsee Node shapes{shape: 'circle', shapeProps: r: 10}Sets a specific SVG shape element + shapeProps to be used for each node.
nodeLabelComponentobjectsee Using foreignObjectsnullAllows using a React component as a node label; requires allowForeignObjects to be set.
onClickfuncundefinedCallback function to be called when a node is clicked.

Has the function signature (nodeData, evt). The clicked node's data object is passed as first parameter, event object as second.
onMouseOverfuncundefinedCallback function to be called when mouse enters the space belonging to a node.

Has the function signature (nodeData, evt). The clicked node's data object is passed as first parameter, event object as second.
onMouseOutfuncundefinedCallback function to be called when mouse leaves the space belonging to a node.

Has the function signature (nodeData, evt). The clicked node's data object is passed as first parameter, event object as second.
onUpdatefuncundefinedCallback function to be called when the inner D3 component updates. That is - on every zoom or translate event, or when tree branches are toggled. The node's data object, as well as zoom level and coordinates are passed to the callback.
orientationstring (enum)horizontal verticalhorizontalhorizontal - Tree expands left-to-right.

vertical - Tree expands top-to-bottom.
translateobject{x: 0, y: 0}Translates the graph along the x/y axis by the specified amount of pixels (avoids the graph being stuck in the top left canvas corner).
pathFuncstring (enum)/funcdiagonal
elbow
straight
customFunc(linkData, orientation)
diagonaldiagonal - Smooth, curved edges between parent-child nodes.

elbow - Sharp edges at right angles between parent-child nodes.

straight - Straight lines between parent-child nodes.

customFunc - Custom draw function that accepts linkData as its first param and orientation as its second.
collapsiblebooltrueToggles ability to collapse/expand the tree's nodes by clicking them.
shouldCollapseNeighborNodesboolfalseIf a node is currently being expanded, all other nodes at the same depth will be collapsed.
initialDepthnumber0..nundefinedSets the maximum node depth to which the tree is expanded on its initial render.
Tree renders to full depth if prop is omitted.
depthFactornumber-n..0..nundefinedEnsures the tree takes up a fixed amount of space (node.y = node.depth * depthFactor), regardless of tree depth.
TIP: Negative values invert the tree's direction.
zoomablebooltrueToggles ability to zoom in/out on the Tree by scaling it according to props.scaleExtent.
zoomnumber0..n1A floating point number to set the initial zoom level. It is constrained by props.scaleExtent. 1 is the default "non-zoomed" level.
scaleExtentobject{min: 0..n, max: 0..n}{min: 0.1, max: 1}Sets the minimum/maximum extent to which the tree can be scaled if props.zoomable is true.
nodeSizeobject{x: 0..n, y: 0..n}{x: 140, y: 140}Sets a fixed size for each node.

This does not affect node circle sizes, circle sizes are handled by the circleRadius prop.
separationobject{siblings: 0..n, nonSiblings: 0..n}{siblings: 1, nonSiblings: 2}Sets separation between neighbouring nodes, differentiating between siblings (same parent) and non-siblings.
transitionDurationnumber0..n500Sets the animation duration (in ms) of each expansion/collapse of a tree node.

Set this to 0 to deactivate animations completely.
textLayoutobject{textAnchor: enum, x: -n..0..n, y: -n..0..n, transform: string}{textAnchor: "start", x: 10, y: -10, transform: undefined }Configures the positioning of each node's text (name & attributes) relative to the node itself.

textAnchor enums mirror the text-anchor spec.

x & y accept integers denoting px values.

transform mirrors the svg transform spec.
stylesobjectsee StylingNode/Link CSS filesOverrides and/or enhances the tree's default styling.
allowForeignObjectsboolsee Using foreignObjectsfalseAllows use of partially supported <foreignObject /> elements.
circleRadius (legacy)number0..nundefinedSets the radius of each node's <circle> element.

Will be deprecated in v2, please use nodeSvgShape instead.

Node shapes

nodeSvgShape 属性允许指定任何 SVG 形状原语描述树的节点应该如何成形。

注意:nodeSvgShapecircleRadius 是互斥的属性。 除非指定旧版 circleRadius,否则将使用 nodeSvgShape

例如,假设我们想使用正方形而不是默认的圆形,我们可以这样做:

const svgSquare = {
  shape: 'rect',
  shapeProps: {
    width: 20,
    height: 20,
    x: -10,
    y: -10,
  }
}

// ...

<Tree data={myTreeData} nodeSvgShape={svgSquare}>

为了避免渲染任何节点元素,只需将 nodeSvgShape 设置为 { shape: 'none' }

Overridable shapeProps

shapeProps 当前与 node.circle/leafNode.circle 合并(参见样式) .

这意味着 shapeProps 中传递的任何属性都将被 node.circle/leafNode.circle< 中具有相同键的属性 覆盖/code> 样式道具。
这是为了防止通过 node/leafNode 属性破坏 circleRadius + 样式的传统用法,直到它在 v2 中被完全弃用。

从 v1.5.x 开始,建议通过 shapeProps 传递所有节点样式属性。

Individual shapeProps

通过将 nodeSvgShape 属性添加到相关节点的数据集,可以将 shapeProps 单独传递给节点。 这允许独立于树的整体 shapeProps 配置设置每个节点的样式、形状和大小(参见 Styling)。

上面的用法示例可以扩展到包括单独的shapeProps

import React from 'react';
import Tree from 'react-d3-tree';

const myTreeData = [
  {
    name: 'Parent Node',
    attributes: {
      keyA: 'val A',
      keyB: 'val B',
      keyC: 'val C',
    },
    nodeSvgShape: {
      shapeProps: {
        fill: 'blue',
      },
    },
    children: [
      {
        name: 'Inner Node',
        attributes: {
          keyA: 'val A',
          keyB: 'val B',
          keyC: 'val C',
        },
        nodeSvgShape: {
          shape: 'rect',
          shapeProps: {
            width: 20,
            height: 20,
            x: -10,
            y: -10,
            fill: 'red',
          },
        },
      },
      {
        name: 'Level 2: B',
      },
    ],
  },
];

...

在上面,“父节点”只会是蓝色的,但它会保持默认的大小和几何形状。 然而,“内部节点”将完全变为具有给定尺寸的红色矩形。 省略 shape,将保持节点的默认外观。

Styling

树的 styles 属性可用于覆盖树的任何默认样式。 styles 需要以下对象形状:

{
  links: <svgStyleObject>,
  nodes: {
    node: {
      circle: <svgStyleObject>,
      name: <svgStyleObject>,
      attributes: <svgStyleObject>,
    },
    leafNode: {
      circle: <svgStyleObject>,
      name: <svgStyleObject>,
      attributes: <svgStyleObject>,
    },
  },
}

其中 是包含与 元素的style 属性,例如:

{
  stroke: 'blue',
  strokeWidth: 3,
}

有关 SVG style 属性的更多信息,检查一下

External data sources

静态托管的 JSON 或 CSV 文件可以通过附加的 treeUtil 模块用作数据源。

Example

import React from 'react';
import { Tree, treeUtil } from 'react-d3-tree';

const csvSource = 'https://raw.githubusercontent.com/bkrem/react-d3-tree/master/docs/examples/data/csv-example.csv';

constructor() {
  super();

  this.state = {
    data: undefined,
  };
}

componentWillMount() {
  treeUtil.parseCSV(csvSource)
  .then((data) => {
    this.setState({ data })
  })
  .catch((err) => console.error(err));
}

class MyComponent extends React.Component {
  render() {
    return (
 &nbsp; &nbsp; &nbsp;{/* <Tree /> will fill width/height of its container; in this case `#treeWrapper` */}
      <div id="treeWrapper" style={{width: '50em', height: '20em'}}>

        <Tree data={this.state.data} />

      </div>
    );
  }
}

有关 treeUtil 模块的详细信息,请查看模块的 API 文档
有关可使用 treeUtil 解析的每种数据类型的示例,请查看数据源示例

Using foreignObjects

⚠️ 由于浏览器支持有限,需要设置 allowForeignObjects 属性:IE 当前不支持 foreignObject 元素

SVG 规范的 foreignObject 元素允许将外部 XML 内容呈现到 SVG 命名空间中,从而解锁了对树图元素使用常规 React 组件的能力。

nodeLabelComponent

nodeLabelComponent 属性提供了一种为每个节点的标签使用 React 组件的方法。 它接受具有以下签名的对象:

{
  render: ReactElement,
  foreignObjectWrapper?: object
}
  • render is the XML React-D3-Tree will use to render each node's label.
  • foreignObjectWrapper contains a set of attributes that should be passed to the <foreignObject /> that wraps nodeLabelComponent. For possible attributes please check the spec.

注意:默认情况下,foreignObjectWrapper 会将其宽度和高度属性设置为 nodeSize.x - 24pxnodeSize .y - 24px 分别; 其中减去 24px 的基本边距以避免元素重叠。 要为每个属性覆盖此行为,请为您的 foreignObjectWrapper 指定 width 和/或 height 属性。

注意:传递给 render 的 ReactElement 是用它现有的 props 克隆的,并且 接收一个额外的 nodeData 对象 prop,包含关于当前的信息node.

Example

假设我们有一个 React 组件 NodeLabel 并且我们希望通过沿 Y 轴移动节点的位置来避免节点的标签与节点本身重叠,我们可以实现 nodeLabelComponent< /代码> 像这样:

class NodeLabel extends React.PureComponent {
  render() {
    const {className, nodeData} = this.props
    return (
      <div className={className}>
        <h2>{nodeData.name}</h2>
        {nodeData._children && 
          <button>{nodeData._collapsed ? 'Expand' : 'Collapse'}</button>
        }
      </div>
    )
  }
}

/* ... */

render() {
  return (
    <Tree 
      data={myTreeData}
      allowForeignObjects
      nodeLabelComponent={{
        render: <NodeLabel className='myLabelComponentInSvg' />,
        foreignObjectWrapper: {
          y: 24
        }
      }}
    />
    )
}

Recipes

React D3 Tree

Greenkeeper badgeBuild StatusCoverage StatusCodacy Badgenpm versionnpm

React D3 Tree is a React component that lets you represent hierarchical data (e.g. ancestor trees, organisational structure, package dependencies) as an animated & interactive tree graph by leveraging D3's tree layout.

Contents

Demo

  • Current release: https://bkrem.github.io/react-d3-tree-demo/

Installation

yarn add react-d3-tree
# or
npm i --save react-d3-tree

Usage

import React from 'react';
import Tree from 'react-d3-tree';

const myTreeData = [
  {
    name: 'Top Level',
    attributes: {
      keyA: 'val A',
      keyB: 'val B',
      keyC: 'val C',
    },
    children: [
      {
        name: 'Level 2: A',
        attributes: {
          keyA: 'val A',
          keyB: 'val B',
          keyC: 'val C',
        },
      },
      {
        name: 'Level 2: B',
      },
    ],
  },
];

class MyComponent extends React.Component {
  render() {
    return (
 &nbsp; &nbsp; &nbsp;{/* <Tree /> will fill width/height of its container; in this case `#treeWrapper` */}
      <div id="treeWrapper" style={{width: '50em', height: '20em'}}>

        <Tree data={myTreeData} />

      </div>
    );
  }
}

Props

PropertyTypeOptionsRequired?DefaultDescription
dataarrayrequiredundefinedSingle-element array containing hierarchical object (see myTreeData above).
Contains (at least) name and parent keys.
nodeSvgShapeobjectsee Node shapes{shape: 'circle', shapeProps: r: 10}Sets a specific SVG shape element + shapeProps to be used for each node.
nodeLabelComponentobjectsee Using foreignObjectsnullAllows using a React component as a node label; requires allowForeignObjects to be set.
onClickfuncundefinedCallback function to be called when a node is clicked.

Has the function signature (nodeData, evt). The clicked node's data object is passed as first parameter, event object as second.
onMouseOverfuncundefinedCallback function to be called when mouse enters the space belonging to a node.

Has the function signature (nodeData, evt). The clicked node's data object is passed as first parameter, event object as second.
onMouseOutfuncundefinedCallback function to be called when mouse leaves the space belonging to a node.

Has the function signature (nodeData, evt). The clicked node's data object is passed as first parameter, event object as second.
onUpdatefuncundefinedCallback function to be called when the inner D3 component updates. That is - on every zoom or translate event, or when tree branches are toggled. The node's data object, as well as zoom level and coordinates are passed to the callback.
orientationstring (enum)horizontal verticalhorizontalhorizontal - Tree expands left-to-right.

vertical - Tree expands top-to-bottom.
translateobject{x: 0, y: 0}Translates the graph along the x/y axis by the specified amount of pixels (avoids the graph being stuck in the top left canvas corner).
pathFuncstring (enum)/funcdiagonal
elbow
straight
customFunc(linkData, orientation)
diagonaldiagonal - Smooth, curved edges between parent-child nodes.

elbow - Sharp edges at right angles between parent-child nodes.

straight - Straight lines between parent-child nodes.

customFunc - Custom draw function that accepts linkData as its first param and orientation as its second.
collapsiblebooltrueToggles ability to collapse/expand the tree's nodes by clicking them.
shouldCollapseNeighborNodesboolfalseIf a node is currently being expanded, all other nodes at the same depth will be collapsed.
initialDepthnumber0..nundefinedSets the maximum node depth to which the tree is expanded on its initial render.
Tree renders to full depth if prop is omitted.
depthFactornumber-n..0..nundefinedEnsures the tree takes up a fixed amount of space (node.y = node.depth * depthFactor), regardless of tree depth.
TIP: Negative values invert the tree's direction.
zoomablebooltrueToggles ability to zoom in/out on the Tree by scaling it according to props.scaleExtent.
zoomnumber0..n1A floating point number to set the initial zoom level. It is constrained by props.scaleExtent. 1 is the default "non-zoomed" level.
scaleExtentobject{min: 0..n, max: 0..n}{min: 0.1, max: 1}Sets the minimum/maximum extent to which the tree can be scaled if props.zoomable is true.
nodeSizeobject{x: 0..n, y: 0..n}{x: 140, y: 140}Sets a fixed size for each node.

This does not affect node circle sizes, circle sizes are handled by the circleRadius prop.
separationobject{siblings: 0..n, nonSiblings: 0..n}{siblings: 1, nonSiblings: 2}Sets separation between neighbouring nodes, differentiating between siblings (same parent) and non-siblings.
transitionDurationnumber0..n500Sets the animation duration (in ms) of each expansion/collapse of a tree node.

Set this to 0 to deactivate animations completely.
textLayoutobject{textAnchor: enum, x: -n..0..n, y: -n..0..n, transform: string}{textAnchor: "start", x: 10, y: -10, transform: undefined }Configures the positioning of each node's text (name & attributes) relative to the node itself.

textAnchor enums mirror the text-anchor spec.

x & y accept integers denoting px values.

transform mirrors the svg transform spec.
stylesobjectsee StylingNode/Link CSS filesOverrides and/or enhances the tree's default styling.
allowForeignObjectsboolsee Using foreignObjectsfalseAllows use of partially supported <foreignObject /> elements.
circleRadius (legacy)number0..nundefinedSets the radius of each node's <circle> element.

Will be deprecated in v2, please use nodeSvgShape instead.

Node shapes

The nodeSvgShape prop allows specifying any SVG shape primitive to describe how the tree's nodes should be shaped.

Note: nodeSvgShape and circleRadius are mutually exclusive props. nodeSvgShape will be used unless the legacy circleRadius is specified.

For example, assuming we want to use squares instead of the default circles, we can do:

const svgSquare = {
  shape: 'rect',
  shapeProps: {
    width: 20,
    height: 20,
    x: -10,
    y: -10,
  }
}

// ...

<Tree data={myTreeData} nodeSvgShape={svgSquare}>

To avoid rendering any node element, simply set nodeSvgShape to { shape: 'none' }.

Overridable shapeProps

shapeProps is currently merged with node.circle/leafNode.circle (see Styling).

This means any properties passed in shapeProps will be overridden by properties with the same key in the node.circle/leafNode.circle style props.
This is to prevent breaking the legacy usage of circleRadius + styling via node/leafNode properties until it is deprecated fully in v2.

From v1.5.x onwards, it is therefore recommended to pass all node styling properties through shapeProps.

Individual shapeProps

shapeProps can be passed to a node individually by adding the nodeSvgShape property to the relevant node's data set. This allows setting each node's style, shape and size independently of the tree's overall shapeProps configuration (see Styling).

The usage example above can be extended to include individual shapeProps:

import React from 'react';
import Tree from 'react-d3-tree';

const myTreeData = [
  {
    name: 'Parent Node',
    attributes: {
      keyA: 'val A',
      keyB: 'val B',
      keyC: 'val C',
    },
    nodeSvgShape: {
      shapeProps: {
        fill: 'blue',
      },
    },
    children: [
      {
        name: 'Inner Node',
        attributes: {
          keyA: 'val A',
          keyB: 'val B',
          keyC: 'val C',
        },
        nodeSvgShape: {
          shape: 'rect',
          shapeProps: {
            width: 20,
            height: 20,
            x: -10,
            y: -10,
            fill: 'red',
          },
        },
      },
      {
        name: 'Level 2: B',
      },
    ],
  },
];

...

In the above, "Parent Node" will only be blue, but it will keep the default size and geometrical shape. "Inner Node", however, will completely change to a red rectangle with the given dimensions. Omitting shape, will keep node's default appearance.

Styling

The tree's styles prop may be used to override any of the tree's default styling. The following object shape is expected by styles:

{
  links: <svgStyleObject>,
  nodes: {
    node: {
      circle: <svgStyleObject>,
      name: <svgStyleObject>,
      attributes: <svgStyleObject>,
    },
    leafNode: {
      circle: <svgStyleObject>,
      name: <svgStyleObject>,
      attributes: <svgStyleObject>,
    },
  },
}

where <svgStyleObject> is any object containing CSS-like properties that are compatible with an <svg> element's style attribute, for example:

{
  stroke: 'blue',
  strokeWidth: 3,
}

For more information on the SVG style attribute, check this out.

External data sources

Statically hosted JSON or CSV files can be used as data sources via the additional treeUtil module.

Example

import React from 'react';
import { Tree, treeUtil } from 'react-d3-tree';

const csvSource = 'https://raw.githubusercontent.com/bkrem/react-d3-tree/master/docs/examples/data/csv-example.csv';

constructor() {
  super();

  this.state = {
    data: undefined,
  };
}

componentWillMount() {
  treeUtil.parseCSV(csvSource)
  .then((data) => {
    this.setState({ data })
  })
  .catch((err) => console.error(err));
}

class MyComponent extends React.Component {
  render() {
    return (
 &nbsp; &nbsp; &nbsp;{/* <Tree /> will fill width/height of its container; in this case `#treeWrapper` */}
      <div id="treeWrapper" style={{width: '50em', height: '20em'}}>

        <Tree data={this.state.data} />

      </div>
    );
  }
}

For details regarding the treeUtil module, please check the module's API docs.
For examples of each data type that can be parsed with treeUtil, please check the data source examples.

Using foreignObjects

⚠️ Requires allowForeignObjects prop to be set due to limited browser support: IE does not currently support foreignObject elements.

The SVG spec's foreignObject element allows foreign XML content to be rendered into the SVG namespace, unlocking the ability to use regular React components for elements of the tree graph.

nodeLabelComponent

The nodeLabelComponent prop provides a way to use a React component for each node's label. It accepts an object with the following signature:

{
  render: ReactElement,
  foreignObjectWrapper?: object
}
  • render is the XML React-D3-Tree will use to render each node's label.
  • foreignObjectWrapper contains a set of attributes that should be passed to the <foreignObject /> that wraps nodeLabelComponent. For possible attributes please check the spec.

Note: By default, foreignObjectWrapper will set its width and height attributes to nodeSize.x - 24px and nodeSize.y - 24px respectively; where a base margin of 24px is subtracted to avoid the overlapping of elements. To override this behaviour for each attribute, specify width and/or height properties for your foreignObjectWrapper.

Note: The ReactElement passed to render is cloned with its existing props and receives an additional nodeData object prop, containing information about the current node.

Example

Assuming we have a React component NodeLabel and we want to avoid node's label overlapping with the node itself by moving its position along the Y-axis, we could implement nodeLabelComponent like so:

class NodeLabel extends React.PureComponent {
  render() {
    const {className, nodeData} = this.props
    return (
      <div className={className}>
        <h2>{nodeData.name}</h2>
        {nodeData._children && 
          <button>{nodeData._collapsed ? 'Expand' : 'Collapse'}</button>
        }
      </div>
    )
  }
}

/* ... */

render() {
  return (
    <Tree 
      data={myTreeData}
      allowForeignObjects
      nodeLabelComponent={{
        render: <NodeLabel className='myLabelComponentInSvg' />,
        foreignObjectWrapper: {
          y: 24
        }
      }}
    />
    )
}

Recipes

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文