为了减少代码的重复和提高开发效率,本人针对React hooks封装了一个echarts公共组件。
使用本组件时,只需要传入以下三个props即可:
- 完整的option对象
- 鼠标点击事件
- 鼠标hover事件
废话不多说,上代码!
import React, { useRef, useEffect } from "react";
import * as echarts from 'echarts'
interface IpProps {
option: Object
onHoverChange: Function
onClickChange: Function
}
let chartId = 'chartDom'
export default (props: IpProps) => {
const { option, onHoverChange = () => { }, onClickChange = () => { } } = props
const chartIns = useRef<any>(null)
/**
* 调用 resize 方法
*/
const resizeAll = () => {
chartIns.current.resize()
}
/**
* 初始化图表组件
*/
useEffect(() => {
const element = document.getElementById(chartId) as HTMLElement
setTimeout(() => {
chartIns.current = echarts.init(element)
chartIns.current.on('click', (params: any) => {
onClickChange(params)
})
chartIns.current.on('mousemove', (params: any) => {
onHoverChange(params)
})
window.removeEventListener('resize', resizeAll)
if (chartIns.current) {
window.addEventListener('resize', resizeAll)
chartIns.current.setOption(option, true)
}
}, 20);
}, [])
/**
* option 发生改变
*/
useEffect(() => {
window.removeEventListener('resize', resizeAll)
if (chartIns.current) {
window.addEventListener('resize', resizeAll)
chartIns.current.setOption(option, true)
}
}, [option])
return (
<div style={{ width: '100%', height: '100%' }} id={chartId} />
)
}