返回

react使用echart图文教程

2023-03-18 react使用echart react echart echart教程 图文教程 2970 0

可以参考ECharts官网的文档:

https://echarts.apache.org/handbook/zh/basics/import

在React中使用ECharts可以通过以下步骤:

安装ECharts库

使用npm或者yarn安装ECharts库:

npm install echarts --save

引入ECharts库

在React项目里需要使用ECharts的组件中,使用import语句引入ECharts库:

import echarts from 'echarts';

在组件中创建一个DOM元素并初始化ECharts

import React, { useState, useEffect } from "react";
import * as echarts from "echarts";
import Box from "@mui/material/Box";
import Loading from "../../components/loading/Loading";

export default function Stock(props) {
  const [showLoading, setShowLoading] = useState(false);
  useEffect(() => {
    const chart = document.getElementById("chart");
    const myChart = echarts.init(chart);
    const option = {
      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",
          showBackground: true,
          backgroundStyle: {
            color: "rgba(180, 180, 180, 0.2)",
          },
        },
      ],
    };
    myChart.setOption(option);
  }, []);

  return (
    <Box>
      <div
        id="chart"
        style={{ minHeight: "400px", width: "100%", marginTop: "10px" }}
      ></div>
      <Loading open={showLoading}></Loading>
    </Box>
  );
}

在组件的render方法中,创建一个元素,然后在componentDidMount或者useEffect方法中,根据元素Id获取元素,然后使用ECharts API来初始化图表并设置图表数据和配置项。

运行效果:

可以设置不同的Option来生成不同的图标。可以参考ECharts官方示例:

https://echarts.apache.org/examples/zh/index.html

您可能感兴趣:

阿里云 云服务器 99元1年 2核2G 3M固定带宽 续费与新购同价

DOVE 网络加速器 梯子 免费 试用

顶部