TypeError: dropdown is null when trying to access Dom element in reactjs

TypeError: dropdown is null when trying to access Dom element in reactjs

请在 react 中遇到此错误,好吧,导入了一些外部 js 文件,在那里进行了某种 Dom 操作,例如添加 css class 和删除 css class 来自我的模板。问题是,当我的 class App.js 加载时,它给我一个错误,即未找到下拉列表 class,根据我自己的理解,我认为这是因为组件尚未呈现。简而言之,请有人帮帮我。提前致谢。

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 class 函数中编写这段代码,.modal 元素位于其中。

componentDidMount(){
    var dropdown = document.querySelector('.modal');
    dropdown.addEventListener('click', function(event) {
        event.stopPropagation();
        dropdown.classList.toggle('is-active');
    });   
}

顺便说一下,你应该使用 onClick 反应的属性而不是像这样绑定点击功能