我正在尝试将Google的Material Design Lite与ReactJS结合使用。我正在使用MDL库的微调器加载和文本字段组件。
但是,当我使用React Router切换路由时,动画不会发生,并且刷新页面后,效果会很好。我认为,这可能是因为MDL组件没有得到升级。然后,我尝试使用componentHandler.upgradeDom(),但Console抛出错误app.js:27160 Uncaught TypeError: Cannot read property 'upgradeDom' of undefined。
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;
我还尝试使用记录控制台中的 MDLite 变量console.log(MDLite)。但是,它向我显示了一个 空的Object {} 。我使用 的WebPack 及安装材料设计精简版与 NPM ,npm install material-design-lite --save。
console.log(MDLite)
npm install material-design-lite --save
我的问题是如何正确导入/要求MDL和使用它componentHandler.upgradeDom()?
我自己想出了解决方案。有两种方法可以实现此目的。
懒惰之路
在中node_modules/material-design-lite/material.js,按如下所述编辑并最后添加以下代码。
node_modules/material-design-lite/material.js
// You can also export just componentHandler if (typeof module === 'object') { module.exports = window; }
您的 material.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 Component文件中,require像这样,
require
var MDLite = require('material-design-lite/material'); var componentHandler = MDLite.componentHandler;
然后,您可以调用componentHandler.upgradeDom()升级MDL元素。
注意,module.exports = componentHandler;如果只想导入,也可以编写componentHandler。
module.exports = componentHandler;
componentHandler
Webpack方式
就个人而言,我更喜欢使用webpack的方式,因为它更清洁,并且您无需自己编辑模块文件。
安装 exports-loader ,npm install exports-loader --save-dev。然后,在 webpack.config.js中 ,将加载程序指定为
npm install exports-loader --save-dev
loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'exports-loader!babel-loader' } ]
在您的React Component文件中,您可以将requirecomponentHandler设置为
var componentHandler = require('exports?componentHandler!material-design-lite/material');
希望对您有所帮助!