React 中使用echrs 图表

59 阅读1分钟
import React, { useEffect } from "react";
import * as echarts from 'echarts';
import { useState } from "react";

const Home = props => {
    const Dj=(cr)=>{
        sessionStorage.setItem('col',JSON.stringify(cr))
    }
    const initChart = () => {
        let element = document.getElementById('chart1');
        let myChart = echarts.init(element);
        myChart.clear()
        let option;
        option = {
            background:color,
            xAxis: {
                type: 'category',
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: [120, 200, 150, 80, 70, 110, 130],
                type: 'bar',
                color:JSON.parse(sessionStorage.getItem('col')),
            }]
        };

        option && myChart.setOption(option);
    }

    useEffect(() => {
        initChart()
         // 设置定时器,在每三秒调用 autoExecuteMethod 方法
         const intervalId = setInterval(autoExecuteMethod, 3000);

         // 在组件卸载时清除定时器
         return () => {
             clearInterval(intervalId);
         };
    }, [])
    const autoExecuteMethod = () => {
        initChart()
    };
    return (
        <div>
            <div id='chart1' style={{ width: '80%', margin: '0 auto', height: '600px' }}></div>
            <button onClick={()=>Dj("red")}>点击</button>
            <button onClick={()=>Dj("blue")}>点击</button>
        </div>
    )
}

export default Home;