React中使用echarts(折线图)

8 篇文章 0 订阅
3 篇文章 0 订阅

组件代码

import React, { Component } from 'react'
import echarts from 'echarts'

class LineEcharts extends Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  // 挂载完成之后,因为React初始化echarts时长宽可能会获取到顶层,所以延迟200去生成,不影响视觉效果
  componentDidMount() {
    setTimeout(() => {
      this.initEchart(this.props.data)
    }, 200)
  }

  // 更新props以后调用
  componentWillReceiveProps(newProps) {
    this.initEchart(newProps.data)
  }

  initEchart = (data) => {
    let myEcharts = echarts.init(this.echartsBox)
    let option = {
      title: {
        text: this.props.title || '',
        left: 'center',
        top: '0'
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            show: false
          }
        },
        formatter: '{b}<br/>汇总:{c}',
        extraCssText: 'box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);'
      },
      xAxis: {
        data: data.x,
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        name: this.props.yname,
        nameGap: 15,
        position: 'left',
        axisTick: {
          inside: true
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      series: [{
        name: '汇总',
        type: 'line',
        data: data.y,
        smooth: false,
        lineStyle: {
          color: '#00CC99',
          width: 2
        },
        itemStyle: {
          color: '#fff',
          borderColor: '#000'
        }
      }]
    }
    myEcharts.setOption(option)
    myEcharts.on('finished', () => {
      myEcharts.resize()
    })
  }

  render() {
    return (
      <div ref={(c) => { this.echartsBox = c }} style={{ width: '100%', height: '100%' }} />
    )
  }
}

export default LineEcharts

使用时

import React, { Component } from 'react'
import LineEcharts from '../components/LineEcharts/index'

class LineEchartsDemo extends Component{
  constructor(props) {
    super(props)
    this.state = {
	    data: {
	      x: ['2019-11-21', '2019-11-22', '2019-11-23', '2019-11-24', '2019-11-25', '2019-11-26'],
	      y: [20, 50, 80, 70, 45, 85]
	    }
    }
  }
  componentDidMount() { }
  render() {
  	<LineEcharts data={this.state.data} yname="单位:件" />  
  }
}

export default LineEchartsDemo 

效果

在这里插入图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值