Use function components to encapsulate ECharts in React to implement simple gradient colors

 Preface: I used class components in React to encapsulate chart instances in Echarts. Now the more I use them, the more I feel that class components encapsulate this thing is really troublesome and not easy to use at all. Function components are better, and I will use them in this article. Function component to simply encapsulate a gradient stacked area chart.

1. Install echarts-for-react and Echarts in the project

npm install --save echarts-for-react  或者 yarn add echarts-for-react

npm install echarts or yarn add echarts

2. Actually complete the gradient form of a stacked area chart.

First initialize and introduce a basic area graphic into Echarts, copy the basic data option and introduce it into your encapsulated component or page.

Complete actual code: (function component form)

import ReactECharts  from "echarts-for-react"
import * as echarts from "echarts"
//定义组件可传参数
type DomProps={   
    wight?:string;
    height?:string;
}
const EchartsDom=(props:DomProps)=>{
    const  option = {
        title: {
          text: 'Stacked Area Chart'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: 'Email',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: 'Union Ads',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310]
          },
          {
            name: 'Video Ads',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [150, 232, 201, 154, 190, 330, 410]
          },
          {
            name: 'Direct',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [320, 332, 301, 334, 390, 330, 320]
          },
          {
            name: 'Search Engine',
            type: 'line',
            stack: 'Total',
            label: {
              show: true,
              position: 'top'
            },
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: [820, 932, 901, 934, 1290, 1330, 1320]
          }
        ]
      };

    return (
        <ReactECharts  option={option} style={
   
   {width:`${props?.wight}`,height:`${props?.height}`}} ></ReactECharts>
    )

}
export  default EchartsDom;

3. Introduce effects (this step is not required if it is not an encapsulated component)

import React from 'react';
import EchartsDom from '@components/EchartsDom';
import './index.css';
const nweflie = () => {
    return (
            <div className='centre'>
                <EchartsDom wight='800px' height='500px'></EchartsDom>
            </div>
    );
};
export default nweflie;

Current renderings:

4. Modify the style and adjust it to gradient

Check out the gradient example of echarts. We can directly color the graphics we need to modify:

The series modification part of option is as follows:

 // 第一组数据的
          {
            name: 'Email',
            type: 'line',
            stack: 'Total',
            // 区域填充样式。
            areaStyle: {
                 //  这里提供一个颜色的变量 transparent 透明色   
                //  在线性渐变中的  LinearGradient中的前四个数值代表方向。
                // 分别为 右 下 左 上,取值范围 0~1
              color: new echarts.graphic.LinearGradient(0,0,0,1,[
                // 0 0 0 1 代表从上到下绘色  
                { offset: 0, color: 'rgba(253, 201, 141, 1)'},  //0 %的颜色
                { offset: 0.5, color: 'rgba(253, 201, 141, 0.6)'},  // 50% 的颜色
                { offset: 1, color: 'rgba(253, 201, 141, 0)' }  //100% 的颜色
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          // 第二组数据的样式
          {
            name: 'Union Ads',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              // 径向渐变 RadialGradient的前三个参数代表 圆心和y、x的半径
              // 分别为 圆心从左到右的位置,圆心在从上到下的位置,圆心的半径 取值为 0~1
              color:new echarts.graphic.RadialGradient(0.5,0.5,0.8,[
                { offset: 0, color: 'rgba(185, 299, 164, 1)'},  // 0% 的颜色
                { offset: 0.5, color: 'rgba(185, 299, 164, 0.5)'}, //50% 的颜色 
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310]
          },

For the time being, we will modify the styles of the two area data. The renderings of these two are as follows:

 

5. Expansion, data transfer.

When encapsulating and using Echarts, the most basic thing is to have data. If you use function components in React to encapsulate Echarts and monitor the data parameters, you can directly use useEffect to monitor changes in props and redraw the chart.

Example:

//先在封装的函数组件中引入 :
import { useEffect } from "react";
//在你的传参配置信息中加入 data;

type DomProps={
    wight?:string;
    height?:string;
    //参数名和参数类型
    data?:any;
}

// 在函数组价中加入以下
const EchartsDom=(props:DomProps)=>{
  //真实数据直接给到你的 option 数据组里
  const [data,setdata]:any=useState([])
  //当props发生变化时,执行以下方法
     useEffect(()=>{
      setdata(props?.data)
  },[props])
  .......略

After defining the parameters in the component, you can directly pass the data when using your component.

For example:

<div className='centre'>
       {/* Data  传递你真实的数据*/}
      <EchartsDom wight='800px' height='500px' data={Data}></EchartsDom>
</div>

 

After being defined in this way, as long as the Data data you pass changes, the corresponding chart will be automatically redrawn.

This article is just a simple record of how React bridges Echarts. There are many interesting settings in the configuration of Echarts that you can continue to explore. The end of this article!

 

Guess you like

Origin blog.csdn.net/youyudehan/article/details/132320181
Recommended