请在反应中出现这个错误,好的,导入了一些外部js文件,在那里做某种Dom操作,如添加css类和从我的模板中删除css类。问题是,当我加载App.js类时,从我自己的理解来看,我认为是找不到该下拉列表类的错误,因为该组件尚未呈现。所以简而言之,请有人可以帮助我。提前致谢 。
js代码
var dropdown = document.querySelector('.modal');
dropdown.addEventListener('click', function(event) {
event.stopPropagation();
dropdown.classList.toggle('is-active');
});
我得到的错误
TypeError: dropdown is null
./src/modules/Restaurants/utils/main.js
C:/Users/user/Desktop/fungry/fungry/src/modules/Restaurants/utils/main.js:2
1 | var dropdown = document.querySelector('.dropdown');
> 2 | dropdown.addEventListener('click', function(event) {
3 | event.stopPropagation();
4 | dropdown.classList.toggle('is-active');
5 | });
将非常感谢
最佳答案
您应该在componentDidMount
元素所在的reactjs类的.modal
函数内编写此代码。
componentDidMount(){
var dropdown = document.querySelector('.modal');
dropdown.addEventListener('click', function(event) {
event.stopPropagation();
dropdown.classList.toggle('is-active');
});
}
顺便说一句,您应该使用react的
onClick
属性,而不是像这样绑定click函数