reactjs React添加和删除EventListener以处理搜索栏

vkc1a9a2  于 2023-01-05  发布在  React
关注(0)|答案(1)|浏览(139)

我不明白为什么我不能摆脱我的eventListener在这段代码。问题是,当我点击搜索图标打开然后关闭搜索栏,'keydown' eventListener不终止,它仍然存在,如果我按Escape键后,它会模糊我的实际组件。你能帮助我吗?
我的代码:

function handleSearchBar(e) {
       let actualComponent = document.querySelector("#actualComponent");
       let searchIcon = document.querySelector("#search_icon");
       if( e.keyCode === 27 || searchIcon.hasAttribute('enabled') ) {
            setSearchBar(() => false)
            searchIcon.toggleAttribute("enabled")
            actualComponent.classList.toggle("blur-sm")
          document.removeEventListener("keydown", handleSearchBar);
            
      }else{

        setSearchBar(() => true)
        searchIcon.toggleAttribute("enabled")
        actualComponent.classList.toggle("blur-sm")
        document.addEventListener("keydown", handleSearchBar);
       }

    }
yyyllmsg

yyyllmsg1#

试试这个。把removeEventListener放到if else之外:

function handleSearchBar(e) {
  let actualComponent = document.querySelector("#actualComponent");
  let searchIcon = document.querySelector("#search_icon");
  if (e.keyCode === 27 || searchIcon.hasAttribute('enabled')) {
    setSearchBar(() => false);
    searchIcon.toggleAttribute("enabled");
    actualComponent.classList.toggle("blur-sm");
  } else {
    setSearchBar(() => true);
    searchIcon.toggleAttribute("enabled");
    actualComponent.classList.toggle("blur-sm");
    document.addEventListener("keydown", handleSearchBar);
  }
  document.removeEventListener("keydown", handleSearchBar);
}

相关问题