react项目中使用echart

1.安装插件

npm install --save echarts-for-react

npm install --save echarts

2.我使用的了父子组件引入方法

父组件:index.js

/**
 * 父组件
 */
import React, { Component } from "react";
import Storage from "store2";
import { Notification, Button, DatePicker } from "antd";
import moment from "moment";
import Request from "@utils/request";
import Echart from "@component/echart";

const chost = Storage.get("chost");
// 格式化时间
const format = "YYYY-MM-DD HH:mm:ss";
class View extends Component {
  constructor(props) {
    super(props);
    this.state = {
      startTime: moment({ hour: 0, minute: 0, seconds: 0 }).subtract(30, "days"), // add(1, "day")
      endTime: moment({ hour: 23, minute: 59, seconds: 59 }),
      backSource: [], // 数据
    };
  }
  UNSAFE_componentWillMount() {
    this.loadData(); // 获取当天数据
  }
  // 渲染页面数据
  loadData = () => {
    const {
      startTime,
      endTime,
    } = this.state;
    // 获取任务列表
    Request.GET(`${chost}/clean/clear`, {
      params: {
        beginDate: moment(startTime).format(format),
        endDate: moment(endTime).format(format),
      }
    }).then((res) => {
      if (res.success) {
        this.setState({
          backSource: res.data
        });
      } else {
        Notification.error({
          message: res.msg || "获取信息失败"
        });
      }
    });
  };
  disabledStartDate = startValue => {
    const { endTime } = this.state;
    if (!startValue || !endTime) {
      return false;
    }
    return startValue.valueOf() > endTime.valueOf();
  };

  disabledEndDate = endValue => {
    const { startTime } = this.state;
    if (!endValue || !startTime) {
      return false;
    }
    return endValue.valueOf() <= startTime.valueOf();
  };
  // 修改开始时间
  changeStartTime = (time) => {
    this.setState({
      startTime: time
    });
  };
  // 修改结束时间
  changeEndTime = (time) => {
    this.setState({
      endTime: time
    });
  };
  render() {
    const {
      startTime,
      endTime,
      backSource,
    } = this.state;
    console.log(backSource);
    return (
      <div className="clear">
        <div className="searchBox">
          <div className="searchItem">
            <span>任务开始时间:</span>
            <DatePicker
              disabledDate={this.disabledStartDate}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              value={startTime}
              placeholder="开始"
              onChange={this.changeStartTime}
              onOpenChange={this.handleStartOpenChange}
            />
          </div>
          <div className="searchItem">
            <span>任务结束时间:</span>
            <DatePicker
              disabledDate={this.disabledEndDate}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              value={endTime}
              placeholder="结束"
              onChange={this.changeEndTime}
            />
          </div>
          <div className="searchItem">
            <Button
              type="primary"
              onClick={() => {
                this.loadData();
              }}
            >
              查询
            </Button>
          </div>
        </div>
        <div className="chartBox">
          <Echart
          backData={backSource}
          xtitle="date"
          />
        </div>
      </div>
    );
  }
}

export default View;

子组件编写echart

import React, { Component } from "react";
import ReactEcharts from "echarts-for-react";
import "echarts/lib/chart/line";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/title"; // 此处是按需引入

class echartLine extends Component {
    constructor(props) {
        super(props);
        this.state = {
          imgType: "line", // 默认折线图
          xtitle: this.props.xtitle, // x轴类目名称取参
        };
    }
    // getOption 这个函数主要用于配置 option,包括将数据配置进去
    // 也可以将其放在 state 中,然后通过 setState 更新
    getOption = () => {
      // 组装数据,返回配置 option
      const {imgType, xtitle} = this.state;
      const dataName =  xtitle === "date" ? "时间" : "名称";
      const currentData = this.props.backData;
      const clearData = {
        name: "清分量",
        type: imgType,
        barWidth : 10,
        data: currentData.map(a => a.cleanAmount) || []
      };
      const linkData = {
        name: "关联量",
        type: imgType,
        barWidth : 10,
        data: currentData.map(b => b.linkAmount) || []
      };
      return {
        color: ["#386db3", "#e5323e"], // 图颜色
        title: {
            text: ""
        },
        tooltip: {
            trigger: "axis"
        },
        legend: {
            data: ["清分量", "关联量"],
            top: "20"
        },
        grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {},
                // dataZoom: {yAxisIndex: "none"}, //区域缩放,区域缩放还原
                //数据视图
                dataView: {
                  readOnly: false,
                  title: "数据视图",
                  // 自定义数据表格样式
                  optionToContent: function (opt) {
                    var axisData = opt.xAxis[0].data;
                    var series = opt.series;
                    var tdHeads = "<td  style=\"padding:5px 10px\">"+ dataName +"</td>";
                    series.forEach(function (item) {
                        tdHeads += "<td style=\"padding: 5px 10px\">"+item.name+"</td>";
                    });
                    var table = "<table border=\"1\" style=\"margin-left:20px;width:600px;border-collapse:collapse;font-size:14px;text-align:center\"><tbody><tr>"+tdHeads+"</tr>";
                    var tdBodys = "";
                    for (var i = 0, l = axisData.length; i < l; i++) {
                        for (var j = 0; j < series.length; j++) {
                            if(typeof(series[j].data[i]) == "object"){
                                tdBodys += "<td>"+series[j].data[i].value+"</td>";
                            }else{
                                tdBodys += "<td>"+ series[j].data[i]+"</td>";
                            }
                        }
                        table += "<tr><td style=\"padding: 0 10px\">"+axisData[i]+"</td>"+ tdBodys +"</tr>";
                        tdBodys = "";
                    }
                    table += "</tbody></table>";
                    return table;
                  }
                },
                magicType: {type: ["line", "bar"]}, //切换为折线图,切换为柱状图
                restore: {},  //还原
            }
        },
        xAxis: {
            type: "category",
            boundaryGap: false,
            data: currentData.map(item => item[xtitle]) || []
        },
        yAxis: {
            type: "value",
            name: "清分量"
        },
        series: [clearData, linkData]
    }
  };
    render() {
      return(
        <ReactEcharts
          style={{ minHeight: "400px" }}
          option={this.getOption()}
          notMerge
          lazyUpdate
          theme={"theme_name"}
          // onChartReady={this.onChartReadyCallback}
          // onEvents={EventsDict}
        />
      )
    }
}

export default echartLine;

效果图如下:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值