教程:在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));
  }

  // func
  forceChart(nodes, edges) {
    this.refs['theChart'].innerHTML = '';

    // 函数内其余代码请看拆解代码
  }

  render() {

    return (
      <Row style={
   { minWidth: 900 }}>
        <div className="outerDiv">
          <div className="theChart" id="theChart" ref="theChart">
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值