react echarts图表封装

先在项目中创建一个文件  用作封装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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值