先在项目中创建一个文件 用作封装echarts图表
在主页面中(也就是父组件中)定义option数据 (如果有使用后台接口数据在useEffect中调用接口 用接口中的数据替换原本的option数据)
然后引入封装的组件 将option传值传过去(父传子)
然后在封装的组件中(子组件)用props接受主页面(父组件)传过来的option 并重新渲染图表在页面中
完整代码
主页面(父)
import * as echarts from 'echarts';
import { useEffect, useRef, useState } from 'react';
import { tu } from '../../request';
// 引入封装组件
import Mycharts from '../../components/mycharts/mycharts';
const Index=()=>{
const [option,setoption] = useState({
legend: {},
tooltip: {},
dataset: {
dimensions: ['product'],
source: [
{ product: 'Matcha Latte', 2015: 43.3, 2016: 85.8, 2017: 93.7 },
{ product: 'Milk Tea', 2015: 83.1, 2016: 73.4, 2017: 55.1 },
{ product: 'Cheese Cocoa', 2015: 86.4, 2016: 65.2, 2017: 82.5 },
{ product: 'Walnut Brownie', 2015: 72.4, 2016: 53.9, 2017: 39.1 }
]
},
xAxis: { type: 'category' },
yAxis: {},
// Declare several bar series, each will be mapped
// to a column of dataset.source by default.
series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' },{ type: 'bar' }]
});
useEffect(()=>{
tu().then(res=>{
console.log('1112',res.data.data)
option.dataset.dimensions=res.data.data[0].dimensions
option.dataset.source=res.data.data[0].source
setoption({...option})
})
},[])
return (
<div style={{width:'300px',height:'300px'}} >
<Mycharts option={option}></Mycharts>
</div>
)
}
export default Index;
封装的页面(子)
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';
const Mycharts=(props)=>{
let box=useRef(null)
let myChart
useEffect(()=>{
myChart=echarts.init(box.current)
myChart.setOption(props.option)
},[props.option])
return(
<div ref={box} style={{width:'100%',height:'100%'}}>
</div>
)
}
export default Mycharts;