本篇文章主要介绍了如何在react中搭建d3力导向图,现在分享给大家,也给大家做个参考。
D3js力导向图搭建
d3js是一个可以基于数据来操作文档的JavaScript库。可以使用HTML,CSS,SVG以及Canvas来展示数据。力导向图能够用来表示节点间多对多的关系。
实现效果:连线有箭头,点击节点能改变该节点颜色和所连接的线的粗细,缩放、拖拽。
版本:4.X
安装和导入
npm安装:npm install d3
前端导入:import * as d3 from 'd3';
一、完整代码import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import * as d3 from 'd3';
import { Row, Form } from 'antd';
import { chartReq} from './actionCreator';
import './Chart.less';
const WIDTH = 1900;
const HEIGHT = 580;
const R = 30;
let simulation;
class Chart extends Component {
constructor(props, context) {
super(props, context);
this.print = this.print.bind(this);
this.forceChart = this.forceChart.bind(this);
this.state = {
};
}
componentWillMount() {
this.props.dispatch(push('/Chart'));
}
componentDidMount() {
this.print();
}
print() {
let callback = (res) => { // callback获取后台返回的数据,并存入state
let nodeData = res.data.nodes;
let relationData = res.data.rels;
this.setState({
nodeData: res.data.nodes,
relationData: res.data.rels,
});
let nodes = [];
for (let i = 0; i < nodeData.length; i++) {
nodes.push({
id: (nodeData[i] && nodeData[i].id) || '',
name: (nodeData[i] && nodeData[i].name) || '',
type: (nodeData[i] && nodeData[i].type) || '',
definition: (nodeData[i] && nodeData[i].definition) || '',
});
}
let edges = [];
for (let i = 0; i < relationData.length; i++) {
edges.push({
id: (relationData[i] && (relationData[i].id)) || '',
source: (relationData[i] && relationData[i].start.id) || '',
target: (relationData[i] && relationData[i].end.id) || '',
tag: (relationData[i] && relationData[i].name) || '',
});
}
this.forceChart(nodes, edges); // d3力导向图内容
};
this.props.dispatch(chartReq({ param: param }, callback));
}
// fun