简体   繁体   English

如何在 ReactJS 中使用事件侦听器?

[英]How can I use event listener in ReactJS?

in tutorials I'm seeing something like that :在教程中,我看到了类似的内容:

import React from 'react';
function App(){ 
  return(
    <div>
    <h1 onClick={functionName}>Hello React</h1>
  </div>
  );

  
}
export default App;

but I think adding "onClick" event to an element is a bad practice , instead we were adding event listener with vanilla JS , but now .但我认为向元素添加“onClick”事件是一种不好的做法,相反,我们使用 vanilla JS 添加事件侦听器,但现在 . I don't know if it is OK or not in reactJS?我不知道在reactJS中是否可以? is there better way or this is what it is ?有没有更好的方法,或者这就是它?

but I think adding "onClick" event to an element is a bad practice但我认为向元素添加“onClick”事件是一种不好的做法

It isn't.不是。 Do not confuse JSX properties with HTML attributes.不要将 JSX 属性与 HTML 属性混淆。


Getting a reference to the element and then using addEventListener in React, on the other hand, is a bad practise as it bypasses React's methods for keeping its internal model in sync with the DOM.另一方面,获取对元素的引用然后在 React 中使用addEventListener一种不好的做法,因为它绕过了 React 保持其内部模型与 DOM 同步的方法。

This is how to do event handling in React.这就是如何在 React 中进行事件处理。 Also take a look at the official documentation.另外看看官方文档。 https://reactjs.org/docs/handling-events.html https://reactjs.org/docs/handling-events.html


import React from 'react';
function App(){ 
  const doSomething = (e) => {
    console.log('event', e)
  }

  return(
    <div>
    <h1 onClick={doSomething}>Hello React</h1>
  </div>
  );

  
}
export default App;

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

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