【问题标题】:How can I use morris.js in React.js?如何在 React.js 中使用 morris.js?
【发布时间】:2020-07-21 04:43:49
【问题描述】:
import React, { useEffect } from "react";
import Raphael from "raphael/raphael";
import "morris.js/morris.js";
import "morris.js/morris.css";

const Test = () => {
  useEffect(() => {
    window.Raphael = Raphael;
    Morris.Donut({
      element: "test",
      data: [
        {
          label: "a",
          value: 49,
        },
        {
          label: "b",
          value: 51,
        },
      ],
      colors: ["#5f76e8", "#01caf1"],
      formatter: function (value, data) {
        return value + "%";
      },
    });
  }, []);
  return <div id="test" />;
};

export default Test;

我想在 React.js 中使用 morris.js。

但是这段代码返回错误。

(第 9:9 行:'Morris' 未定义)

但是,就在此错误短语出现之前,饼图短暂可见,但很快错误短语立即出现。

我该如何使用它?

【问题讨论】:

    标签: javascript node.js reactjs morris.js


    【解决方案1】:

    有几种方法可以解决这个问题。如果你提到的包是umdcommonjs的类型,你可以要求直接使用:

    const yourModule = import('morris.js/morris.js')
    

    或者,如果您将包加载为外部(例如 CDN 站点),我假设您现在是 webpack 作为捆绑器,那么您只需在您的 webpack.config.js 中配置它:

    externals : {
     morris: "Morris"
    },
    

    在您的 html 模板中,index.html 看起来像:

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
    

    然后您只需导入以在您的模块中使用:

    import morris from "morris"
    

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 2014-09-28
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多