我正在使用Webpack和Babel将项目移动到ES6来编译代码。这就是我现在所拥有的:
entry.js
import Header from './components/header';
(function() {
const header = new Header();
})();
header.js
export default class Header {
constructor() {
this.bodyTag = document.querySelector('body');
this.toggleNavigationButton = document.querySelector('#toggleNavigationButton');
this.toggleNavigationButton.addEventListener('click', this.toggleMobileNavigation());
}
toggleMobileNavigation() {
this.bodyTag.classList.toggle('CLICK');
}
}
webpack.config.js
module.exports = {
entry: "./js/entry.js",
output: {
filename: "./js/bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
};
问题是,当页面加载时,方法toggleMobileNavigation
被触发,click
事件根本不起作用。
我错过了什么?
答案 0 :(得分:2)
这是因为你的回调有括号,然后立即调用,尝试删除它们:
this.toggleNavigationButton.addEventListener('click', this.toggleMobileNavigation);