2021-03-16

react中使用echarts,并实现tooltip循环轮播

查看效果

实现代码

查看效果

当我们开发数据看板类需求时,需要图标实现自动轮播的效果,具体效果如下


实现代码

这里整个图表为一个组件,通过传data和配置入组件来显示

按需加载echarts组件

react生命钩子中实现echarts的resize事件

当传入的props数据发生变化后需要重新渲染echarts


import React, { Component } from 'react'

import { Empty } from 'antd'

import echarts from 'echarts/lib/echarts'

import 'echarts/lib/chart/line'

import 'echarts/lib/component/tooltip'

import 'echarts/lib/component/markLine'

import 'echarts/lib/component/title'

class LineBarShow extends Component {

echartsObj = null

loopTooltipTimer = null

state = {

  xAxisData: [],

  seriesData: []

}

componentDidMount () {

window.addEventListener('resize', this.chartResize)

}

chartResize = () => {

setTimeout(() => {

  this.echartsObj && this.echartsObj.resize()

}, 100)

}

componentWillUnmount () {

window.removeEventListener('resize', this.chartResize)

this.loopTooltipTimer = null

}

// 当props发生改变--start

// 当props发生变化后将值赋给当前组件的state变量

static getDerivedStateFromProps (nextProps, prevState) {

  return {

    xAxisData: nextProps.data.xAxisData,

    seriesData: nextProps.data.seriesData

  }

}

loopShowTooltip = () => {

  let index = 0

  this.loopTooltipTimer = setInterval(() => {

    this.echartsObj.dispatchAction({

      type: 'showTip',

      seriesIndex: 0,

      dataIndex: index

    })

    // 循环轮播

    index = this.state.xAxisData.length - 1 ? 0 : ++index

  }, 1000)

}

componentDidUpdate () {

let { xAxisData } = this.state

if (xAxisData && xAxisData.length) {

this.echartsObj = echarts.init(document.getElementById(this.props.id))

let option = {...}

this.echartsObj.setOption(option)

// 这里可以加判断,是否需要循环轮播

// 这里默认显示

this.loopShowTooltip()

}

}

// 当props发生改变--end

render () {

let { xAxisData } = this.state

    return (

      <div className="full-height">

        { xAxisData && xAxisData.length ? (

          <div id={this.props.id} className="full-height"></div>

        ) : (

          <Empty />

        )}

      </div>

    )

}

}

————————————————

版权声明:本文为CSDN博主「土豆Coder涮火锅」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/weixin_43443341/article/details/105511713

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容