react+ echarts 轮播饼图
图片示例
代码
import * as echarts from 'echarts';
import { useEffect } from 'react';
import styles from './styles.scss';
const Student = (props) => {
const { dataList, title } = props;
// 过滤数据
const visionList = [
{ value: 1048, name: 'Search Engine'},
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
];
useEffect(() => {
loadingChart();
}, [dataList])
const loadingChart = () => {
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('Student'));
// 指定图表的配置项和数据
var option = {
tooltip: {
trigger: 'item'
},
series: [
{
name: '学生统计',
type: 'pie',
radius: ['56%', '84%'],
data: visionList,
color: ['#52CCB8', '#61C2F2', '#36B580', '#619DF2', '#2E8AE5'],
emphasis: { // 设置高亮时显示标签
label: {
show: true
},
scale: true, // 设置高亮时放大图形
scaleSize: 20
},
label: { // 设置图形标签样式
show: false, // 未高亮时不显示标签,否则高亮时显示的标签会与静态的标签重叠
position: 'center',
// 设置标签展示内容,其中{d}、{b}为echarts标签内容格式器
formatter: '{d_style|{d}}{per_style|%}\n{b_style|{b}}',
// 为标签内容指定样式,只能设置series-pie.label支持的样式
rich: {
d_style: {
fontSize: 20
},
per_style: {
fontSize: 20
},
b_style: {
fontSize: 18
}
}
}
}
]
}
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
if (visionList.length <= 0) {
myChart.showLoading({
text: '暂无数据',
showSpinner: false,
textColor: '#fff',
maskColor: 'rgba(0, 0, 0, 0)',
fontSize: '18px'
})
} else {
myChart.hideLoading()
}
let currentIndex = -1; // 当前高亮图形在饼图数据中的下标
let changePieInterval = setInterval(selectPie, 1000); // 设置自动切换高亮图形的定时器
function highlightPie() { // 取消所有高亮并高亮当前图形
for (var idx in option.series[0].data)
// 遍历饼图数据,取消所有图形的高亮效果
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: idx
});
// 高亮当前图形
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: currentIndex
});
}
myChart.on('mouseover', (params) => { // 用户鼠标悬浮到某一图形时,停止自动切换并高亮鼠标悬浮的图形
if (changePieInterval)
clearInterval(changePieInterval);
currentIndex = params.dataIndex;
highlightPie();
});
myChart.on('mouseout', (params) => { // 用户鼠标移出时,重新开始自动切换
if (changePieInterval)
clearInterval(changePieInterval);
changePieInterval = setInterval(selectPie, 1000);
});
function selectPie() { // 高亮效果切换到下一个图形
var dataLen = option.series[0].data.length;
currentIndex = (currentIndex + 1) % dataLen;
highlightPie();
}
}
return (
<div id='Student' style={{ width: '77%', height: '250px', float: 'right', color: '#fff' }}></div>
);
};
export default Student;