Echarts封装
src/component/chart
封装Chart组件,在里面完成Echart实例的初始化和点击事件的绑定。
index.tsx
export const Chart = observer((props: IChartProps) => {
const { option, loading, onClickEvent } = props;
const chartContainerRef = useRef<HTMLDivElement>();
const chartRef = useRef<echarts.ECharts>(null);
initChart(chartContainerRef, chartRef);
if (onClickEvent) handleClickEvent(chartRef, onClickEvent);
updateOptions(chartRef, option);
return (
<Spin className="spin-container" spinning={loading}>
<div className="chart-container" ref={chartContainerRef} />
</Spin>
);
});
init-chart.tsx
export const initChart = (
chartContainerRef: React.MutableRefObject<HTMLDivElement>,
chartRef: React.MutableRefObject<echarts.ECharts>
) => {
useEffect(() => {
const myChart = echarts.init(chartContainerRef.current);
chartRef.current = myChart;
return () => {
chartRef.current.dispose();
};
}, []);
};
export const updateOptions = (
chartRef: React.MutableRefObject<echarts.ECharts>,
option: EChartOption<unknown>
) => {
useEffect(() => {
chartRef.current.clear();
chartRef.current.setOption(option);
}, [option]);
};
export const handleClickEvent = (
chartRef: React.MutableRefObject<echarts.ECharts>,
onClickEvent: (p: IEchartEventParams) => void
) => {
useEffect(() => {
chartRef.current.on('click', onClickEvent);
}, []);
};
使用
src/container/xxx
具体的数据在Store里面拼好。
@observer
export class XXX extends React.Component {
render() {
<div className="xxx">
<Chart
option={xxxStore.data.option}
loading={xxxStore.getLoading(xxx)}
onClickEvent={(p) => {
// sth
}}
/>
)}
</div>
}
}