react中使用echarts(人物关系图)
项目中有时会用到echarts,可能不同的框架中语法稍有变通,前几天在react项目中遇到,写此篇以作记录。
不同的charts语法跟支持不同,本篇"echarts": "^4.2.0-rc.2"
前期准备
cnpm i -S echarts
import echarts from 'echarts/lib/echarts'; //必须
import "echarts/lib/chart/graph"; //引入折线图(按需)
import'echarts/lib/chart/line’ //引入折线图(按需)
App.jsx
import echarts from 'echarts/lib/echarts';
import "echarts/lib/chart/graph";
import options from './options'; //echarts相关配置
componentDidMount(){
let myChart = echarts.init(document.getElementById('main'));
//若有数据交互此处改变渲染数据,保留原有样式与配置
if(res.data.nodes){
options.series[0].data=res.data.nodes;
options.series[0].links=res.data.links;
}
// 绘制图表
myChart.setOption(options);
//一些事件
myChart.on('click', params=> {
...
console.log(params.data);
});
}
render() {
return (
<div className='atlas-wrap'>
<div id="main"></div> //可通过id设置样式
</div>
)
}
options.js
export default {
title: {
text: ''
},
tooltip: {},
animationDurationUpdate: 1500,
animationEasingUpdate: 'quinticInOut',
label: {
normal: {
show: true,
textStyle: {
fontSize: 12
},
}
},
legend: {
x: "center",
show: false,
data: ["夫妻", "战友", '亲戚']
},
series: [
{
type: 'graph',
layout: 'force',
symbolSize: 45,
focusNodeAdjacency: true,
roam: true,
categories: [{
name: '夫妻',
itemStyle: {
normal: {
color: "#009800",
}
}
}, {
name: '战友',
itemStyle: {
normal: {
color: "#4592FF",
}
}
}, {
name: '亲戚',
itemStyle: {
normal: {
color: "#3592F",
}
}
}],
label: {
normal: {
show: true,
textStyle: {
fontSize: 12
},
}
},
force: {
repulsion: 1000
},
edgeSymbolSize: [4, 50],
edgeLabel: {
normal: {
show: true,
textStyle: {
fontSize: 10
},
formatter: "{c}"
}
},
data: [{
name: 'Mary',
draggable: true,
}, {
name: 'Tom',
category: 1,
draggable: true,
}, {
name: 'Allen',
category: 1,
draggable: true,
}, {
name: 'Kevin',
category: 1,
draggable: true,
}, {
name: 'Rose',
category: 1,
draggable: true,
}],
links: [{
source: 0,
target: 1,
category: 0,
value: '夫妻'
}, {
source: 0,
target: 2,
value: '子女'
}, {
source: 0,
target: 3,
value: '夫妻'
}, {
source: 0,
target: 4,
value: '父母'
}, {
source: 1,
target: 2,
value: '表亲'
}],
lineStyle: {
normal: {
opacity: 0.9,
width: 1,
curveness: 0
}
}
}
]
}
相关配置文档:
http://echarts.baidu.com/option.html#series-graph
参考文档:http://gallery.echartsjs.com/explore.html?u=bd-2135947294&type=work#sort=rank~timeframe=all~author=all