react 项目中 echarts 点击事件 和 轮播项 配置
react 项目中 引入 和离开页面注销 echarts
import * as echarts from 'echarts'; let equipEchart: any = null; let BarEchartsTimer: any = null; // 定时器 useEffect(() => { const dom = document.getElementById('equipEchart') as HTMLDivElement; equipEchart = echarts.init(dom); window.onresize = () => { equipEchart.resize(); // 页面缩放 }; return () => { equipEchart.dispose(); equipEchart = null; clearInterval(BarEchartsTimer); BarEchartsTimer = null; }; }, []);
点击事件两种方法,
一种是`myChart.on('click',(val)=>{})`, 大多数需求都可以用 这种方法就能实现,
点击整块区域是因为 多条柱状图 可能只有其中一条有数据, 但是需求是没有数据的柱状图只要点击就要有效果
用的 `myChart.getZr().on('click',,(val)=>{})` , 点击一块区域算出来是第几条数据来实现的
// 点击数据 myChart.on('click', (v) => { getList(list[v.dataIndex].k, list[v.dataIndex].t); }); // 点击区域 myChart.getZr().on('click', (params) => { let pointInPixel = [params.offsetX, params.offsetY]; if (myChart.containPixel('grid', pointInPixel)) { let ind = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[0]; // 点击区域的下标 } });
定时器实现轮播效果
let fn = () => { let tooltipIndex = 0; clearInterval(BarEchartsTimer); BarEchartsTimer = setInterval(() => { myChart.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: tooltipIndex, }); tooltipIndex++; if (tooltipIndex > xData.length) { tooltipIndex = 0; } }, 2000); }; if (xData.length) { fn(); // 定时器轮播 }
react 点击事件 + 轮播(多条柱状图 )
const equipEcharts = (myChart: any, list: Array) => { let xData = []; // x轴 let seriesArr: [any] = []; // 多条柱状图数据 let option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: function (params) {}, }, dataZoom: [ { type: 'inside', start: 0, end: 100, height: 20 }, // 区域缩放 { start: 0, end: 100, height: 20 }, ], xAxis: { type: 'category', data: xData, axisLine: { show: false }, axisTick: { show: false }, axisLabel: { color: '#666666' }, }, yAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%', color: '#666666' }, axisLine: { show: true, lineStyle: { color: '#eeeeee' } }, // 轴线样式 splitLine: { show: true, lineStyle: { color: '#eeeeee', type: 'dashed' }, }, // 分隔线 axisTick: { show: false }, // 刻度 }, series: seriesArr, }; myChart.setOption(option); let fn = () => { let tooltipIndex = 0; clearInterval(BarEchartsTimer); BarEchartsTimer = setInterval(() => { myChart.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: tooltipIndex, }); tooltipIndex++; if (tooltipIndex > xData.length) { tooltipIndex = 0; } }, 2000); }; if (xData.length) { fn(); // 定时器轮播 } myChart.getZr().on('click', (params) => { let pointInPixel = [params.offsetX, params.offsetY]; if (myChart.containPixel('grid', pointInPixel)) { let ind = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)[0]; // 点击区域的下标 } }); };