需求
大屏项目需要让元素动起来才好看,因此条形需要自动轮播,鼠标移入后停止轮播,移除后再次开始轮播。
效果
代码
import React, { useEffect, useRef, useState } from 'react';
import { useInterval, useUpdateEffect, useHover } from 'ahooks';
import * as echarts from 'echarts';
const timing = 1500;
const yDataSource = ['Mon', 'Tue', 'Wed', 'Thu'];
const xDataSource = [
{
name: 'Affiliate Ad',
data: [220, 182, 191, 234],
},
{
name: 'Video Ad',
data: [150, 212, 201, 154],
},
{
name: 'Search Engine',
data: [820, 832, 901, 934],
},
];
const option: echarts.EChartsOption = {
title: {
text: '堆叠条形图',
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
},
},
legend: {
// data: ['Affiliate Ad', 'Video Ad', 'Search Engine'],
show: true,
top: 30,
},
grid: {
left: '3%',
right: '5%',
bottom: '3%',
containLabel: true,
},
xAxis: {
type: 'value',
},
yAxis: {
type: 'category',
data: yDataSource,
},
series: xDataSource.map((item) => ({
name: item.name,
data: item.data,
type: 'bar',
stack: 'total',
barWidth: '50%',
label: {
show: true,
},
emphasis: {
focus: 'series',
blurScope: 'coordinateSystem',
},
})),
};
export default () => {
const chartRef = useRef<any>();
const myChart = useRef<echarts.ECharts>();
const [interval, setInterval] = useState<number | undefined>(undefined);
const [count, setCount] = useState(0);
const setTooltip = (index: number) => {
if (myChart.current) {
myChart.current.dispatchAction({
type: 'hideTip',
});
myChart.current.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: index,
});
}
};
// 移入时取消轮播
const isHovering = useHover(() => chartRef.current);
useUpdateEffect(() => {
setInterval(isHovering ? undefined : timing);
}, [isHovering]);
// 自动轮播
useInterval(() => {
setCount((prev) => (prev >= yDataSource?.length - 1 ? 0 : prev + 1));
}, interval);
useUpdateEffect(() => {
setTooltip(count);
}, [count]);
useEffect(() => {
if (!myChart.current && chartRef?.current) {
myChart.current = echarts.init(chartRef.current);
if (myChart?.current) {
myChart.current.setOption(option);
setTooltip(0);
setInterval(timing);
}
}
}, []);
return <div style={{ width: '100%', height: '100%' }} ref={chartRef} />;
};
出现的问题
echarts 自带 mouseover
在鼠标移入画布时不生效,即使使用了 getZr()
依然不生效。事件只会在鼠标移入某个具体区域才生效,移入画布空白区域不生效。(click、mouseout
等其他事件有效)
因此不用自带的鼠标事件,而是用 ahooks 中的 useHover 事件进行监听。