简体   繁体   English

React.js 上的 addEventListener

[英]addEventListener on React.js

I'm trying to run an addEventListener function on a React app, but most of the times it doesn't run as expected.我正在尝试在 React 应用程序上运行 addEventListener 函数,但大多数时候它没有按预期运行。

Not sure if I need to remake it or if its missing something.不确定我是否需要重新制作它,或者它是否缺少某些东西。 If so, can you guys help me with that?如果是这样,你们能帮我吗?

const light = document.querySelector('.light');
const grid  = document.querySelector('.grid-container, .navbar, #hex-grid');
  if (light){
      grid.addEventListener('mousemove', function (e) {
      light.style.left = `${e.clientX}px`;
      light.style.top = `${e.clientY}px`;
    });
  };

the line in the code const grid = document.querySelector('.grid-container, .navbar, #hex-grid');代码中的行const grid = document.querySelector('.grid-container, .navbar, #hex-grid'); is wrong.if you need to access many element in the jquery you have to querySelectorAll();是错误的。如果您需要访问 jquery 中的许多元素,则必须 querySelectorAll(); function.功能。 execute below code,执行以下代码,

let grids= document.querySelectorAll("'.grid-container, .navbar, #hex-grid');

Then you can use JavaScript map function add event listener by looping through the nodes array in the grid variable.然后,您可以通过遍历网格变量中的节点数组来使用 JavaScript 映射函数添加事件侦听器。

grids.map(grid=>(

  grid.addEventListener('mousemove', function (e) {
      light.style.left = `${e.clientX}px`;
      light.style.top = `${e.clientY}px`;
    });

));

I didnt add the const light = document.querySelector('.light');我没有添加const light = document.querySelector('.light'); since you mentioned the logic and what you need too do using light class node.因为您提到了逻辑以及使用轻类节点还需要做什么。 I only referring the the bug in your code.我只指您代码中的错误。

I changed to querySelector the whole app div ('.App').我更改为 querySelector 整个应用程序 div('.App')。 Seems to work fine.似乎工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM