- 必须用ID,不能用className 否则会报错 无法找到该dom元素
- 必须在componentDidMount或之后的生命周期才能初始化echarts, 因为,dom元素可能还没挂载完成, 无法找到该dom元素
- dom容器必须设置宽、高,否则无法看到效果
主要代码(忽略一些不相关的代码):
我只展示全局引入,按需引入请参照官网https://echarts.baidu.com/tutorial.html#%E5%9C%A8%20webpack%20%E4%B8%AD%E4%BD%BF%E7%94%A8%20ECharts
const echarts = require('echarts')
componentDidMount() {
this.showBarChart(this.state.myChartData)
}
showBarChart = dataSet => {
var myChart = echarts.init(document.getElementById('BarWrap'))
const option = {
legend: {},
tooltip: {},
dataset: {
dimensions: ['product', '2015', '2016', '2017'],
source: [
{ product: 'Matcha Latte', '2015': 43.3, '2016': 85.8, '2017': 93.7 },
{ product: 'Milk Tea', '2015': 83.1, '2016': 73.4, '2017': 55.1 },
{ product: 'Cheese Cocoa', '2015': 86.4, '2016': 65.2, '2017': 82.5 },
{ product: 'Walnut Brownie', '2015': 72.4, '2016': 53.9, '2017': 39.1 },
],
},
xAxis: { type: 'category' },
yAxis: {},
series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }],
}
myChart.setOption(option)
}
render() {
return (
<div style={{ width: '100%', height: 300 }} id="BarWrap" />
)
}