I have search about this problem.
It must be pass function reference.
document.addEventListener("click", () => {}, false)
But what I do is still fire immediately.
Do I make some wrong?
Test code is below
export default function App() {
const start = () => {
console.log("start");
};
const click1 = () => {
document.addEventListener("click", start);
};
const click2 = () => {
const element = document.getElementById("p");
element.addEventListener("click", start);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={click1}>Click1</button>
<hr />
<p id="p">123</p>
<button onClick={click2}>Click2</button>
</div>
);
}
// Click1 - immediately, problem here
// Click2 - no immediately
https://codesandbox.io/s/reverent-grass-5fok7b?file=/src/App.js
What I expect
click first, add click event, no anything is log.
click second, log 'start'
actually output
click first, add click event, log start
.