使用Morris.js与Reactjs

4

我如何使用reactjs创建morris.js图表? 我正在使用带有react.js库的Asp.net MVC5项目。这是我的第一个react项目,我想在单击某个按钮时更改morris.js图表。我不想在react js脚本中使用其他react库,只想使用morris js库。

2个回答

4

以下是如何让Morris.js与React配合使用的方法。

  1. 安装Morris.js及其依赖项Raphael.js:
npm install --save-dev morris.js
npm install --save-dev raphael
  1. 在您的组件中:
import Raphael from 'raphael';
import 'morris.js/morris.css';
import 'morris.js/morris.js';

3. Morris要求Raphael在全局范围内。
constructor() {
    super();
    window.Raphael = Raphael;
}

重要提示

  1. 如果您在编译时出现对 morris.css 的编译错误,请阅读这篇文章

  2. 如果您写成 import Morris from 'morris.js/morris.js',它将不会起作用。

  3. 还有一种方法可以使 Raphael 处于全局范围内。

const webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            Raphael: 'raphael'
        })
    ],
    ...
}

如果您喜欢这个变体,您就不需要:
import Raphael from 'raphael';
window.Raphael = Raphael;

尝试了这个解决方案,但是我得到了一个"ReferenceError: jQuery未定义"的错误,我不知道为什么。我已经安装了jQuery,因为我也有boostrap。 - Mr_LinDowsMac
我会确保在调用Raphael和Morris脚本之前先调用jQuery。 - Arsen K.
完成。但是在尝试像@novasaint提供的答案中那样使用它之后,我遇到了一个错误。 - Mr_LinDowsMac

1

简单的解决方案

componentDidMount() 中绘制你的图表,例如我使用的是甜甜圈图:

yourChart = Morris.Donut({ element: 'elementId', data: data, // ...other options });

其中 yourChart 在类外声明,或者你可以在 constructor() 中使用 this.yourChart

如果你想要更新/重新绘制你的图表,在按钮点击时,你可以调用 yourChart.setData(newData)


谢谢您的回答。我在互联网上找到了这个框架:http://recharts.org/,它对我很有帮助。 - Aggounix
现在我得到了一个 TypeError: morris_js_morris_js__WEBPACK_IMPORTED_MODULE_3___default.a.Area 不是一个函数 - Mr_LinDowsMac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接