javascript - 带有 ReactJS 的 Material Design Lite(导入/要求问题)

标签 javascript reactjs npm webpack material-design-lite

我正在尝试使用 Google's Material Design Lite使用 ReactJS。我正在使用 Spinner Loading & Text Field MDL 库的组件。

但是,当我使用 React Router 切换路由时,动画不会发生,当我刷新页面时,它工作正常。我想,这可能是因为 MDL 组件没有升级。然后,我尝试使用 componentHandler.upgradeDom(),但控制台抛出错误,app.js:27160 Uncaught TypeError: Cannot read property 'upgradeDom' of undefined

这是代码,

var React = require('react');
var ReactDOM = require('react-dom');
var PropTypes = React.PropTypes;
var MDLite = require('material-design-lite');
var componentHandler = MDLite.componentHandler;

var styles = {
  loader: {
    marginTop: '70px',
  }
}

var Loading = React.createClass({
  render: function() {
    return (
      <div className="mdl-spinner mdl-js-spinner is-active" style={styles.loader}></div>
    );
  },
  componentDidMount: function() {
    componentHandler.upgradeDom();
  },
});

module.exports = Loading;

我还尝试使用 console.log(MDLite) 在控制台中记录 MDLite 变量。但是,它向我展示了一个空对象{}。我正在使用 webpack 并安装了带有 NPM 的 Material Design Lite,npm install material-design-lite --save

我的问题是如何正确导入/要求 MDL 并使用 componentHandler.upgradeDom()

最佳答案

我自己想出了解决方案。您可以通过两种方式实现这一目标。

The Lazy Way

node_modules/material-design-lite/material.js 中,编辑并在最后添加以下代码,如下所述。

// You can also export just componentHandler
if (typeof module === 'object') {
  module.exports = window;
}

您的 ma​​terial.js 文件将如下所示。

;(function() {
  .
  .
  .
  componentHandler.register({
    constructor: MaterialRipple,
    classAsString: 'MaterialRipple',
    cssClass: 'mdl-js-ripple-effect',
    widget: false
  });

  // You can also export just componentHandler
  if (typeof module === 'object') {
    module.exports = window;
  }

}());

在你的 React 组件文件中,像这样require

var MDLite = require('material-design-lite/material');
var componentHandler = MDLite.componentHandler;

然后,您可以调用componentHandler.upgradeDom()来升级MDL元素。

请注意,如果您只想导入 componentHandler,也可以编写 module.exports = componentHandler;

The Webpack Way

就我个人而言,我更喜欢 webpack 方式,因为它更简洁,而且您无需自己编辑模块文件。

安装exports-loadernpm install exports-loader --save-dev。然后,在您的 webpack.config.js 中,将加载器指定为

loaders: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'exports-loader!babel-loader'
  }
]

在你的 React Component 文件中,你可以require componentHandler as

var componentHandler = require('exports?componentHandler!material-design-lite/material');

希望对您有所帮助!

关于javascript - 带有 ReactJS 的 Material Design Lite(导入/要求问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809425/

相关文章:

javascript - 无需滚动即可使用 Javascript 显示页面上的所有元素

javascript - react .js : Dynamically create complex DOM from nested JSON before rendering

gruntjs - grunt 不会安装或安装不正确

javascript - 使用 nth-child 选择器选择元素

javascript - 我应该选择哪个 redux 中间件?

javascript - javascript 中的 Ajax Url 模式验证

javascript - 如何同步 Redux 状态和 url 哈希标签参数

css - 如何使用带 react 动画的样式组件制作滑入和滑出

node.js - 使用 --生产选项和对等依赖项进行 npm install

javascript - 在 netlify 中部署 React 应用程序时出现问题