React+Echarts簡單的封裝套路


今天我們來介紹一下React中,對Echarts的一個簡單的封裝。

首先在我們的React項目中,想使用Echart包,首先需要先安裝它,安裝代碼如下,任選一個就可以

cnpm install echarts --save
npm install echarts --save
yarn add echarts --save

安裝好之后,新建一個JS文件,命名test.js,首先導入的是各種依賴(總代碼在文章結尾)

import React from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/markPoint';
import 'echarts/lib/component/markLine';

Echeart是需要對真實DOM進行渲染的,且必須用ID不能用className,所以在componentDidMount生命周期的時候,就需要get這個圖表的id進行初始化,如:

let myChart = echarts.init(document.getElementById('myTable'));

但是反過來想一想,當你需要多次使用該組件的時候,你會發現如果是固定id的時候會出現問題,因為id只能有一個,所以這里會有兩種處理方式:

1、如果你習慣於在這個組件留下能操控的id,你可以在給這個組件傳值的時候,傳入一個id參數,這樣可以自己手動保證id不重復,還能在組件外能CSS或JS操作這個圖標。

let { id } = this.props.data;
let myChart = echarts.init(document.getElementById( id ? id : 'myTable'));

2、如果你不需要留下自己操作的id,可以使用隨機的id,這樣不用留神是否id重復的問題(以下代碼已省略部分)

let getRandomID = () => Number(Math.random().toString().substr(4, 10) + Date.now()).toString(36)
let id = getRandomID();
class Test extends React.Component {
    componentDidMount() {
        window.addEventListener("resize", function () {
            myChart.resize();
        });
        // 初始化
        let myChart = echarts.init(document.getElementById(id));
    render() {
        return (
            <div id={id}></div>
        );
    }
}

export default Test;

初始化完成后,使用圖表是當然需要使用數據的,我們當然是不希望數據是只能固定一排或者兩排的,所以我們應該在組件外傳入不定量的數據,然后在組件中自動去初始化這個圖表,這里我的傳入數據有:圖表標題、x軸名、y軸數據、y軸數據所對應的項目名、該圖表的高度和寬度、id。以下就是我的組件代碼:

import React from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/markPoint';
import 'echarts/lib/component/markLine';

const defaultType = 'bar';
const defaultWidth = '100%';
const defaultHeight = '300px';
let getRandomID = () => Number(Math.random().toString().substr(4, 10) + Date.now()).toString(36)
let id = getRandomID();
class Test extends React.Component {
    componentDidMount() {
        window.addEventListener("resize", function () {
            myChart.resize();
        });
        // 初始化
        let { title, xdata, ydata, legend } = this.props.data;
        let myChart = echarts.init(document.getElementById(id));
        let series = [];
        for (let i = 0; i < ydata.length; i++) {
            let item = {
                name: legend[i],
                type: defaultType,
                data: ydata[i],
                markPoint: {
                    data: [
                        { type: 'max', name: '最大值' },
                        { type: 'min', name: '最小值' }
                    ]
                },
                markLine: {
                    data: [
                        { type: 'average', name: '平均值' }
                    ]
                }
            }
            series.push(item)
        }
        // 繪制圖表
        myChart.setOption({
            title: { text: title },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: legend
            },
            toolbox: {
                show: true,
                feature: {
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: {
                        show: true,
                        type: 'jpg'
                    }
                }
            },
            xAxis: [
                {
                    type: 'category',
                    data: xdata
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series
        });
    }
    render() {
        let { width, height } = this.props.data;
        return (
            //默認高寬
            <div id={id} style={{ width: width ? width : defaultWidth, height: height ? height : defaultHeight }}></div>
        );
    }
}

export default Test;

這樣封裝好了之后,我們的調用就很舒服,無論是傳幾條數據在ydata里面都可以。

import React, { Component } from 'react'
import Test from './Test'

class All extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className="all">
                    <Test data={{
                        id: 'mainmain',
                        width: '100%',
                        height: '500px',
                        title: '某地區新增男孩人數、女孩人數和總人數',
                        xdata: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                        ydata: [[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                        [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
                        [4.6, 10.8, 16, 50, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6]],
                        legend: ['男孩', '女孩', '總人數']
                    }} />
            </div>
        )
    }
}

export default All

這是一個非常簡單,但是實用的封裝,不止是在Echarts,在很多其他的地方,大家都可以用到這么一套方法來封裝自己的組件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM