英文:
One element having two onClick events with opposite useState
问题
import React, { useState } from "react";
export default function App() {
const [showList, setShowList] = useState(false);
return (
<div className="" onClick={() => setShowList(false)}>
<h1>Welcome Here</h1>
<button onClick={() => setShowList(true)}>Click here</button>
{showList && (
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
)}
</div>
);
}
英文:
I'm trying to use a custom dropdown with a useState
hook. I want to show the list when button is clicked but want to hide when user clicks anywhere outside the button. So, I'm having onClick
events on parent div and button, but the onClick
event of parent div triggers even when clicking the button, preventing the button to show the list.
Here is the code:
import React, { useState } from "react";
export default function App() {
const [showList, setShowList] = useState(false);
return (
<div className="" onClick={() => setShowList(false)}>
<h1>Welcome Here</h1>
<buton onClick={() => setShowList(true)}>Click here</buton>
{showList && (
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
)}
</div>
);
}
And this is the codesandbox example: https://codesandbox.io/s/custom-dropdown-ycq90y?file=/src/App.js:0-426
答案1
得分: 1
你需要停止事件的传播:
<button
onClick={(event) => {
event.stopPropagation() // <--- 这会阻止事件冒泡到树上层
setShowList(true)
}}
>
点击这里
</button>
这并不是React特有的,React只是为其合成事件包装了本地行为。
英文:
You need to stop the propagation of the event:
<button
onClick={(event) => {
event.stopPropagation() // <--- this makes the event not bubble up the tree
setShowList(true)
}}
>
Click here
</button>
This is not React specific, React is only wrapping the native behaviour for it's synthetic events.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论