思路:
外层只需要传入options即可进行渲染操作
import { useState, useEffect , useRef} from 'react';
import * as echarts from 'echarts';
import { generateMixed } from '../../utils/common';
import './index.css';
export default function EchartInit(props: any) {
// 传入options配置项
const { options } = props;
const [echartID, setEchartID] = useState<string>('kop');
const echartRef = useRef(null);
let echart = null;
useEffect(() => {
setEchartID(generateMixed(32));
},[])
useEffect(() => {
// 生成32位随机码当dom元素ID
let dom = document.getElementById(echartID);
// 实例化echart对象
echart = echarts.init(dom as HTMLElement);
// 渲染
echart && echart.setOption(options)
}, [options])
return (
<div id={echartID} ref={echartRef} className='echart-content'></div>
)
}
index.css
.echart-content {
height: 100%;
width: 100%;
}
生成随机码
export function generateMixed(n: number) {
var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var res = "";
for (var i = 0; i < n; i++) {
var id = Math.floor(Math.random() * 62);
res += chars[id];
}
return res;
}