最近项目有数据统计展示的需求,考虑使用echarts,在开发的过程中遇到挺多问题,本文就这开发过程做个小结。
Taro版本:3.0.7
echarts插件:使用了taro物料市场的echarts插件
物料地址: https://taro-ext.jd.com/plugin/view/5f648e4c0dd8313026e0942d
npm i echarts-taro3-react
import React, { Component } from 'react'
import { View } from '@tarojs/components'
import { EChart } from 'echarts-taro3-react'
import './index.scss'
class Pie extends Component {
static defaultProps={
data: []
}
componentDidMount() {
this.refresh()
}
refresh() {
const { data } = this.props
const option = {
// 提示配置
tooltip: {
trigger: 'item',
formatter: '{b}:{c} ({d}%)'
},
// 图例配置
legend: {
orient: 'vertical',
icon: 'circle',
left: 0,
top: 'middle',
formatter: function(name) {
let target
for (let i = 0, l = data.length; i < l; i++) {
if (data[i].name === name) {
target = data[i].value
}
}
return `${name}(${target})`
}
},
// 颜色配置
color: ['#68DAA5', '#648BF8', '#F4BD37', '#75C6EB'],
// 数据配置
series: [
{
type: 'pie',
left: 58,
data,
label: {
show: false
}
}
]
}
this.pieChart.refresh(option)
}
refPieChart = (node) => (this.pieChart = node);
render() {
return (
<View className='pie-chart'>
<EChart ref={this.refPieChart} canvasId='pie-chart' />
</View>
)
}
}
export default Pie
.pie-chart{
width: 100%;
height: 300px;d
}
import React, { Component } from 'react'
import { View } from '@tarojs/components'
import Pie from './pie/index'
import './index.scss'
class Statistics extends Component {
render() {
return (
<View className='chart'>
<Pie data={data} />
</View>
)
}
}
export default Statistics
import React, { Component } from 'react'
import { View } from '@tarojs/components'
import { EChart } from 'echarts-taro3-react'
import './index.scss'
class Line extends Component {
static defaultProps = {
xData: [],
yData: []
}
componentDidMount() {
this.refresh()
this.props.onRef(this)
}
refresh() {
const { xData, yData } = this.props
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: xData
},
yAxis: {
type: 'value'
},
series: [{
data: yData,
type: 'line',
smooth: true,
itemStyle: {
color: '#009C9C'
},
lineStyle: {
color: '#009C9C'
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [{
offset: 0, color: '#009C9C' // 0% 处的颜色
}, {
offset: 1, color: 'white' // 100% 处的颜色
}]
}
}
}]
}
this.lineChart.refresh(option)
}
refLineChart = (node) => (this.lineChart = node);
render() {
return (
<View className='line-chart'>
<EChart ref={this.refLineChart} canvasId='line-chart' />
</View>
)
}
}
export default Line
line.scss
与饼图同理
父组件引入
由于要根据时间范围更新折线图所以父组件要使用子组件的refresh方法
// render 传入onRef指向子组件环境
<View className='chart'>
<Line onRef={(ref) => { this.Line = ref }} xData={xData} yData={yData} />
</View>
// 更新 让refresh延迟触发不然会更新不了折线图
Taro.nextTick(() => { this.Line.refresh() })
// or
setTimeout(() => {
this.Line.refresh()
}, 0);