React以Hook的方式使用Echarts

背景

目前组内在开发的项目使用的虽然是React,但是并不是之前的类式组件,所以写法有不少的区别,经过查阅之后,现以Hook的方式使用Echarts,在此进行总结,方便之后的学习。

步骤

安装Echarts

首先引入Echarts的模块

npm install echarts --save

如果你使用的是 Typescript ,那么还需要引入 @types/echarts

npm install @types/echarts --save
代码中引入Echarts

有两种方式,二选其一,按需引入全部引入,各有优劣,各位可自行选择

按需引入

代码如下,使用了echarts,line,tooltip,legend

import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/title'
import 'echarts/lib/component/tooltip'

按需引入的优点是最后打包生成的文件较小,一般会采用这种方法

全部引入
import echarts from 'echarts'
使用Echarts

React自从新增了Hook特性以后,使用函数式组件,需要改动一定的地方。

使用useEffect代替之前的初始化函数

这部分建议查看官方文档

提示
如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。

初始化图表
使用getElementById初始化

综上,可以在 useEffect 中写原先在 componentDidMount() 的初始化图表的函数

let element = document.getElementById('main');
let myChart = echarts.init(element as HTMLDivElement);
let option = {
    title: {
        text: 'ECharts 入门示例',
    },
    tooltip: {
    },
    legend: {
        data:['销量', '利润', '比率']
    },
    xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    },
    yAxis: {
    },
    series: [
        {
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
        },
        {
            name: '利润',
            type: 'bar',
            data: [30, 25, 15, 20, 20, 35]
        },
        {
            name: '比率',
            type: 'line',
            data: [35, 30, 20, 25, 25, 40]
        }]
    };
myChart.setOption(option);

DOM中代码如下

<div>
    <div id={'main'} style={{height: 400}}/>
</div>
使用Ref引用初始化

除了上述的使用getElementById的方法以外,还可以使用ref引用的方式,如以下代码所示,最后在useEffect里调用renderChart

 const main2 = useRef(null);
 let chartInstance = null;

 let renderChart = () => {
     const myChart = echarts.getInstanceByDom(main2.current as unknown as HTMLDivElement);
     if(myChart)
         chartInstance = myChart;
     else
         chartInstance = echarts.init(main2.current as unknown as HTMLDivElement);
     chartInstance.setOption({
         title: {
             text: '燃尽图'
         },
         tooltip: {
             trigger: 'axis'
         },
         toolbox: {
             feature: {
                 saveAsImage: {}
             }
         },
         legend: {
             data: ['Remain', 'Ideal']
         },
         xAxis: {
             boundaryGap: false,
             type: 'category',
             data: ['1-1', '1-2', '1-3', '1-5', '1-6', '1-7', '1-8', '1-9']
         },
         yAxis: {
             type: 'value'
         },
         series: [
             {
                 name: 'Remain',
                 data: [140, 110, 100, 90, 70, 30, 10, 0],
                 type: 'line'
             },
             {
                 name: 'Ideal',
                 data: [140, 120, 100, 80, 60, 40, 20, 0],
                 type: 'line'
             }
         ]
     })
 };

DOM中代码如下

<div>
    <div style={{height: 400}} ref={main2}/>
</div>
整体代码

整体的代码如下所示

import React, {useEffect, useRef, useState} from "react";
import echarts from 'echarts';

const Test: React.FC =  () => {
    const main2 = useRef(null);
    let chartInstance = null;

    let renderChart = () => {
        const myChart = echarts.getInstanceByDom(main2.current as unknown as HTMLDivElement);
        if(myChart)
            chartInstance = myChart;
        else
            chartInstance = echarts.init(main2.current as unknown as HTMLDivElement);
        chartInstance.setOption({
            title: {
                text: '燃尽图'
            },
            tooltip: {
                trigger: 'axis'
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            legend: {
                data: ['Remain', 'Ideal']
            },
            xAxis: {
                boundaryGap: false,
                type: 'category',
                data: ['1-1', '1-2', '1-3', '1-5', '1-6', '1-7', '1-8', '1-9']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: 'Remain',
                    data: [140, 110, 100, 90, 70, 30, 10, 0],
                    type: 'line'
                },
                {
                    name: 'Ideal',
                    data: [140, 120, 100, 80, 60, 40, 20, 0],
                    type: 'line'
                }
            ]
        })
    };

    let initChart = () => {
        let element = document.getElementById('main');
        let myChart = echarts.init(element as HTMLDivElement);
        let option = {
            title: {
                text: 'ECharts 入门示例',
            },
            tooltip: {
            },
            legend: {
                data:['销量', '利润', '比率']
            },
            xAxis: {
                data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
            },
            yAxis: {
            },
            series: [
                {
                    name: '销量',
                    type: 'bar',
                    data: [5, 20, 36, 10, 10, 20]
                },
                {
                    name: '利润',
                    type: 'bar',
                    data: [30, 25, 15, 20, 20, 35]
                },
                {
                    name: '比率',
                    type: 'line',
                    data: [35, 30, 20, 25, 25, 40]
                }]
        };
        myChart.setOption(option);
    };
    
    useEffect(() => {
        initChart();
        renderChart();
    });

    return(
        <div>
            <div id={'main'} style={{height: 400}}/>
            <div style={{height: 400}} ref={main2}/>
        </div>
    );
};

export default Test

最终效果

最后的结果如下图所示
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值