echarts-for-react图表自适应与适配屏幕
echarts图表集
1.解决图表自适应
图表一些参数无法使用rem
- 基础图表
import EChartsReact from 'echarts-for-react';
<EChartsReact
showLoading={loading} // 加载状态
loadingOption={{ // 加载样式
maskColor: 'rgba(87,168,255,0.1)',
color: '#00D5FF',
textColor: '#E1EFFE',
text: '加载中...',
spinnerRadius: 20,
}}
option={option} // 图表配置项
style={{ height: '100%', width: '100%' }}
/>
- 添加页面监听页面变化重新渲染图表
useEffect(() => {
const myChart = echarts && echarts.getEchartsInstance();
window.addEventListener('resize', () => { // 监听页面变化
if (myChart) {
myChart.resize(); // 调用重新渲染图表函数
}
});
}, []);
<EChartsReact
ref={(e) => { // 获取echarts实例
if (e) {
echarts = e;
}
}}
showLoading={loading}
loadingOption={{
maskColor: 'rgba(87,168,255,0.1)',
color: '#00D5FF',
textColor: '#E1EFFE',
text: '加载中...',
spinnerRadius: 20,
}}
option={option}
style={{ height: '100%', width: '100%' }}
/>
- 解决页面变化图表与文字大小问题
/**
* rem宽度适配计算
* @param res 设计稿大小
* @returns 计算后大小
*/
const calculation= (res: any) => {
const clientWidth =
window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (!clientWidth) return;
const multipleWidth = clientWidth / 1920; // 设计图宽度
return res * multipleWidth;
};
const option={
title: {
text: '领域分布'.split('').join('\n'),
left: 'left', // 标题水平安放位置,可选值为'left'、'center'、'right'或具体的水平坐标值
top: 'center', // 标题垂直安放位置,可选值为'top'、'bottom'、'center'或具体的垂直坐标值
textStyle: {
fontSize: calculation(14), //使用
color: '#FFFFFF',
lineHeight: calculation(24), //字体行高
fontFamily: 'PingFang SC',
},
}}
useEffect(() => {
const myChart = echarts && echarts.getEchartsInstance();
window.addEventListener('resize', () => { // 监听页面变化
if (myChart) {
myChart.setOption(option); // 将重新计算的option配置项加入
myChart.resize(); // 调用重新渲染图表函数
}
});
}, []);
2.解决设置100%宽度却为100px问题 =延时加载组件=
useEffect(() => {
setTimeout(() => {
setShow(true);
});
}, []);
{show ? (
<EChartsReact
key={keyId}
showLoading={showLoading}
option={option}
style={{ height, width: '100%' }}
/>
) : null}
3.react + echarts 的事件方法
const incident = {
click: (e: any) => {
console.log(e, '点击事件');
},
};
<EChartsReact
showLoading={loading}
loadingOption={{
maskColor: 'rgba(87,168,255,0.1)',
color: '#00D5FF',
textColor: '#E1EFFE',
text: '加载中...',
spinnerRadius: 20,
}}
option={option}
style={{ height: '100%', width: '100%' }}
onEvents={incident} // 事件添加
/>