you must register event listener in React Hooks
try this
import React, { useEffect, useState, useRef } from "react";
export default function App() {
const [counter, setCounter] = useState(0);
const buttonEl = useRef(null);
useEffect(() => {
console.log(counter);
}, [counter]);
useEffect(() => {
const alertFunc = function () {
alert("-----");
}
const buttonRef = buttonEl.current;
buttonRef.addEventListener(
"click",
alertFunc,
false
);
// Specify how to clean up after this effect:
return function cleanup() {
buttonRef.removeEventListener("click", alertFunc, false)
};
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button className="btn" ref={buttonEl}> set countor</button>
</div>
);
}
I register listener in hooks, and when the component will unmount I remove the listener
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…