admin管理员组文章数量:1389750
Let's say I have a button that only fires just once then the listener is removed. I've done this with vanilla Javascript
const element = document.querySelector('#MyElement');
element.addEventListener('click', handleClick, {once: true});
I don't know how can I access this property with React synthetic events since this is putted directly in the ponent
<button id="MyElement" onClick={handleClick}>Click me!</button>
Thanks
Let's say I have a button that only fires just once then the listener is removed. I've done this with vanilla Javascript
const element = document.querySelector('#MyElement');
element.addEventListener('click', handleClick, {once: true});
I don't know how can I access this property with React synthetic events since this is putted directly in the ponent
<button id="MyElement" onClick={handleClick}>Click me!</button>
Thanks
Share Improve this question asked Jan 8, 2021 at 7:37 ChimiChimi 331 silver badge4 bronze badges 04 Answers
Reset to default 4You can use useRef
to do the same. Demo link is here
import React, { useEffect, useRef } from "react";
export default function App() {
const ref = useRef();
useEffect(() => {
if (ref.current) {
ref.current.addEventListener("click", () => console.log('Clicked only once'), { once: true });
}
}, []);
return (
<div>
<button ref={ref}>Click on me (Once)</button>
</div>
);
}
const [avoidExtraCall, setAvoidExtraCall] = useState(false);
const handleClick = () => {
if(!avoidExtraCall){
//Do what you want here then
setAvoidExtraCall(true);
//This if statement will only be executed once
}
}
return (
<button id="MyElement" onClick={handleClick}>
Click me!
</button>
);
You can use a variable in state, probably a boolean for this
function App {
const [buttonClicked, setButtonClicked] = useState(false);
const handleClick = () => {
setButtonClicked(true);
// continue with the function
}
return <button onClick = {
buttonClicked ? () => {} : handleClick
} > Click < /button>
}
Or you could just return from the handleClick
function App {
const [buttonClicked, setButtonClicked] = useState(false);
const handleClick = () => {
if(buttonClicked){
return; //simply return
}
setButtonClicked(true);
// continue with the function
}
return <button onClick={handleClick}> Click </button>
}
I would prefer the second option.
Flip the state once the element has triggered its event :
handleClick() {
this.setState({
hasTriggered: true
})
}
render() {
return (
<div>
{
!this.state.hasTriggered ?
<MyElement onClick={this.handleClick.bind(this)} /> : null
}
</div>
)
}
本文标签: javascriptReactHow can I fire an Event listener just onceStack Overflow
版权声明:本文标题:javascript - React - How can I fire an Event listener just once? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744722343a2621767.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论