在 React 的 Function 组件中使用 addEventListener

在 React 的函数组件中使用 addEventListener

Using addEventListener in Function components in React

addEventListener在 React 的函数组件中使用方法:

  1. ref在元素上设置道具。
  2. 使用currentref 上的属性来访问元素。
  3. useEffect在钩子中添加事件侦听器。
应用程序.js
import {useRef, useEffect} from 'react'; const App = () => { const ref = useRef(null); useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []); return ( <div> <button ref={ref}>Click</button> </div> ); }; export default App;

react 函数组件添加事件监听器

useEffect我们在功能组件的钩子中为元素添加了一个事件监听器。

如果要向window, 或对象添加事件侦听器,请使用相同的方法,但不包括. document ref

The useRef() hook can be
passed an initial value as an argument. The hook returns a mutable ref object
whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the button element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets
the .current property of the ref object to the corresponding DOM node.

We passed an empty dependencies array to the
useEffect hook, so
it’s only going to run when the component mounts.

We only want to call the addEventListener method once – when the component
mounts.

App.js
useEffect(() => { const handleClick = event => { console.log('Button clicked'); }; const element = ref.current; element.addEventListener('click', handleClick); return () => { element.removeEventListener('click', handleClick); }; }, []);

We stored the a reference to the element in a variable and used the
addEventListener
method to add a click event listener to the button.

The first parameter the method takes is the type of the event to listen for, and the second is a function that gets invoked when an event of the specified type occurs.

The function we returned from the useEffect hook is called when the component
unmounts.

We used the
removeEventListener
method to remove the event listener that we previously registered.

The cleanup step is important, because we want to make sure we don’t have any
memory leaks in our application.