- 移动端自适应 - echarts)">Media Query 实现(移动端自适应 - echarts)
- echarts 的 resize 实现
Media Query 实现(移动端自适应 - echarts)
性能高、效果好,适用多个图表。
echarts 的 resize 实现
改变图表尺寸,在容器大小发生改变时需要手动调用。性能低,只适用单个图表。
实现
import React from 'react';
import { useSize, useUpdateEffect } from 'ahooks';
interface ResponsChartsProps {
myChart: React.MutableRefObject<any>;
chartRef: React.MutableRefObject<any>;
}
const ResponsCharts: React.FC<ResponsChartsProps> = ({ myChart, chartRef }) => {
const size = useSize(chartRef);
useUpdateEffect(() => {
myChart?.current?.resize();
}, [size]);
return null;
};
export default ResponsCharts;
使用
import { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import ResponsCharts from './ResponsCharts';
import styles from './index.less';
const option: echarts.EChartsOption = {
...
};
export default () => {
const chartRef = useRef<HTMLDivElement>(null);
const myChart = useRef<echarts.ECharts>();
const initChart = () => {
if (!myChart.current && chartRef?.current) {
myChart.current = echarts.init(chartRef.current);
myChart.current.setOption(option);
}
};
useEffect(() => {
initChart();
}, []);
return (
<div style={{ width: '100%', height: '100%' }}>
<div style={{ width: '100%', height: '100%' }} ref={chartRef} />
<ResponsCharts myChart={myChart} chartRef={chartRef} />
</div>
);
};