我在使用 Materialize-css 和 React 时遇到问题。我使用 Webpack 和 Babel 构建了它。问题是:
TypeError: $(...).parallax is not a function
TypeError: $(...).material_chip is not a function
TypeError: $(...).modal is not a function
etc.
这是我的 React 类:
import React from 'react';
import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';
class AwesomeComponent extends React.Component {
constructor(props) {
super(props);
}
onLike () {
$('.modal').modal();
}
render() {
return (
<div>
<div id="modal1" className="modal">
<div className="modal-content">
<h4>Modal Header</h4>
<p>A bunch of text</p>
</div>
<div className="modal-footer">
<a href="#!" className=" modal-action modal-close waves-effect waves-green btn-flat">Agree</a>
</div>
</div>
<a className="waves-effect waves-light btn" onClick={this.onLike}>
<i className="material-icons left">
cloud
</i>
Like cloud
</a>
</div>
);
}
}
export default AwesomeComponent;
这是我的 webpack.config.js 的一部分,它导入 jQuery:
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
这是我的 package.json 的一部分:
"dependencies": {
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"materialize-css": "^0.98.0",
"react": "^15.4.1",
"react-dom": "^15.4.1",
"webpack": "^1.13.3",
"jquery": "^2.1.4"
},
请帮帮我,我已经尝试了一切。
我已经调试过了。它向 $ 原型(prototype)添加了插件(例如 .modal),但不知何故,当我想在类中使用它时,这些功能消失了。
最后这是一个堆栈跟踪:
TypeError: $(...).modal is not a function[Learn More] bundle.js:44497:14
onLike
bound onLike
ReactErrorUtils.invokeGuardedCallback
executeDispatch
executeDispatchesInOrder executeDispatchesAndRelease
executeDispatchesAndReleaseTopLevel
forEach forEachAccumulated
EventPluginHub.processEventQueue
runEventQueueInBatch
ReactEventEmitterMixin.handleTopLevel
handleTopLevelImpl
TransactionImpl.perform
ReactDefaultBatchingStrategy.batchedUpdates
batchedUpdates
ReactEventListener.dispatchEvent
bound
最佳答案
对于有同样问题的其他人。
不要在 webpack.config.js 中使用 webpack.ProvidePlugin 并且不要导入 $ 或 jQuery。 Materialise 将为您提供。
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
为此,请在 jsx 文件顶部使用以下代码:
import 'materialize-css';
并且不要忘记适当的加载器,这对于 Materialise 很重要:
loaders : [
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader?importLoaders=1', 'sass-loader'],
exclude: ['node_modules']
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader?importLoaders=1'],
exclude: ['node_modules']
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel-loader', 'babel-loader?presets[]=react,presets[]=es2015'],
}
]
关于javascript - Materialise 不支持 React、Webpacka。 jQuery 未扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42421787/