react hooks使用echarts

安装依赖

npm install echarts --save

项目需要的是柱状图,如图

在这里插入图片描述

组件

 <ChartBar
	id="chart-bar"
	optionsData={echarts}
	width={880}
	height={300}
 />

组件内容,全粘过来了

import {useEffect} from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';

const ChartBar = props => {
    const {optionsData = null, id = 'default-id', width = 600, height = 200} = props;
    useEffect(() => {
        let xData = [];
        let yData = [];
        optionsData && optionsData.map(item => {
            if (item.code === null) {
                item.code = '暂无';
            }
            xData.push(item.code);
            yData.push(item.count);
        });
        const option = {
            color: ['#3541AF'],
            title: '',
            grid: {
                left: '8%',
                right: '0',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: '#fff',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (params) {
                    let res = `<div style="color: #333333;">类型:${params[0].name}</div>`
                         + `<div style="color: #333333;">数量:${params[0].value}台</div>`;
                    return res;
                }
            },
            xAxis: {
                data: xData,
                axisLine: {
                    lineStyle: {
                        color: '#999999'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#999999'
                    }
                }
            },
            yAxis: {
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#999999'
                    }
                }
            },
            series: [{
                type: 'bar',
                barWidth: '20%',
                data: yData
            }]
        };
        const chart = echarts.init(document.getElementById(id));
        chart.setOption(option);
    }, [optionsData]);
    return (
        <div id={id} style={{width: width, height: height}}>222</div>
    );
};

export default ChartBar;

然后就可以了,具体需要什么样的echarts去官网学习,如果没有出来,一定是写的有问题,代码不会骗人!


版权声明:本文为zcfzfc123456789原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。