React Hook(ts)里面使用eacharts
React Hook(ts)里面使用eachartsimport React, { useState, useEffect } from "react";import styles from "./echarts.less"; // 样式import * as echarts from "echarts";import { parseInt } from "lodash";const PublicCharts = (props: any) => { const [selectIndex, setSelectIndex] = useState<number>(0); var myChart: any = null; const [num, setNum] = useState(0); useEffect(() => { // 设置 num,让图表只进行一次初始化 if (num == 0) { if (!myChart) { myChart = echarts.init( document.getElementById("main") as HTMLDivElement ); } } setNum(num + 1); }, []); function chartsData() { if (!myChart) { myChart = echarts.init( document.getElementById("main") as HTMLDivElement ); } var addNum = 0; // 接收传入数据的总条数 props.areaData.forEach((item: any) => { addNum += item.values.length; }); var option: any; // 如果父组件传来的数据不为空 if (addNum > 0) { option = { tooltip: { trigger: "axis", }, legend: { data: props.areaData.map((item: any) => { return item.key; }), x: "right", y: "top", }, grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true, }, xAxis: { type: "time", // type为time时,不要传xAxis.data的值,x轴坐标的数据会根据传入的时间自动展示 boundaryGap: false, // false横坐标两边不需要留白 axisLabel: { // x轴显示 formatter: function (value: string | number | Date, index: any) { const date = new Date(value); const texts = [ date.getFullYear(), date.getMonth() + 1, date.getDate(), ]; return texts.join("-"); }, }, }, yAxis: { type: "value", axisTick: { show: true, }, }, // 对传来的数据直接处理 series: props.areaData.map((item: any) => { return { symbol: "none", name: item.key, type: "line", data: item.values.map((res: { x: any; y: any }) => { return [res.x, res.y]; // type为time是, data要是二维数组([[x, y],[x, y]] x为时间 y数值) }), }; }), }; }else { const main = document.getElementById("areaMain") as HTMLDivElement; main.innerHTML = `<h2 class=${styles.headerContH}>暂无数据</h2>`; } // 传来的数据改变, 图标更新 option && myChart?.setOption(option, true); } useEffect(() => { chartsData(); // react中图表的点击事件(这里获取时间) myChart.getZr().on("click", function (params: any) { const echartsData = [params.offsetX, params.offsetY]; const echartsDate = myChart.convertFromPixel( { seriesIndex: 0 }, echartsData ); if (echartsDate) { let year = new Date(parseInt(echartsDate[0])).getFullYear(); let month = new Date(parseInt(echartsDate[0])).getMonth(); let date = new Date(parseInt(echartsDate[0])).getDate(); props.funTable(`${year}-${month + 1}-${date}`); } }); // 解决重复 init的报错 return () => { myChart && myChart.dispose(); }; }, [props.areaData]); return ( <> <div id="main" style={{ width: "100%", height: "400px" }}></div> </> ); };export default PublicCharts;
来源:https://www.cnblogs.com/Sir-Chu/p/14793973.html