5-react中使用echarts

1、echarts-for-react

安装依赖

npm i echarts
npm i echarts-for-react

代码示例

import ReactEcharts from 'echarts-for-react';

2、原生echarts

代码示例

import React from 'react';
import echarts from 'echarts/lib/echarts';

class TestCharts extends React.Component {
  state = {};
  componentDidMount() {
    // 基于准备好的dom,初始化echarts实例
    const myChart = echarts.init(document.getElementById('main'));
    // 绘制图表
    myChart.setOption({
      title: { text: 'ECharts 入门示例' },
      tooltip: {},
      xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
      },
      yAxis: {},
      series: [{
        name: '销量',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20]
      }]
    });
  }
  render() {
    return (
      
); } } export default TestCharts;

3、动态数据或者再次渲染

  • 原生setOption
  • echarts-for-react setOption用ref
myRef = React.createRef();
this.myRef.current.getEchartsInstance().setOption(newOption);
        
  • cloneDeep
import cloneDeep from 'lodash/cloneDeep';

      const newOption = cloneDeep(this.state.option); // immutable
      newOption.xAxis.data = cloneDeep(date);
      newOption.series[0].data = cloneDeep(data);
      this.setState({
        option: newOption,
      });

你可能感兴趣的:(5-react中使用echarts)