英文:
How to close dropdown on click outside React TypeScript?
问题
我有一个下拉菜单,需要在单个页面的多个位置使用。
当我打开任何一个下拉菜单时,其他的下拉菜单应该关闭。我该如何解决这个问题?
我的代码:
Code Sandbox
英文:
I have a dropdown & I need to use this dropdown in multiple places in single page.
When I open any dropdown then rest of the dropdown should be close. How can I fix this issue ?
My code:
Code Sandbox
答案1
得分: 1
以下是您提供的代码的翻译部分:
import React, { useState } from "react";
const Dropdown = () => {
const [actionIsOpen, setActionIsOpen] = useState<boolean>(false);
const actionList = [
{ id: "1", name: "One" },
{ id: "2", name: "Two" },
{ id: "3", name: "Three" },
{ id: "4", name: "Four" }
];
const handleActionClick = () => {
setActionIsOpen((prev) => !prev);
};
return (
<>
<div className="tw-relative">
<span onMouseDown={handleActionClick} className="tw-cursor-pointer">
<button onBlur={() => setActionIsOpen(false)}>Dropdown Click</button>
</span>
{actionIsOpen && (
<div className="shadow tw-w-48 tw-absolute tw-top-2 tw-z-50 tw-left-4 tw-bg-white tw-pt-2">
{actionList.map((val: any) => (
<div
key={val.id}
className="tw-bg-white-100 hover:tw-bg-violet-100 hover:tw-text-violet-900 tw-cursor-pointer hover:tw-font-bold py-2 px-3 tw-text-gray-600"
onMouseDown={() => alert(val.name)}
>
{val.name}
</div>
))}
</div>
)}
</div>
</>
);
};
export default Dropdown;
希望这对您有所帮助!如果您需要进一步的帮助,请随时提出。
英文:
import React, { useState } from "react";
const Dropdown = () => {
const [actionIsOpen, setActionIsOpen] = useState<boolean>(false);
const actionList = [
{ id: "1", name: "One" },
{ id: "2", name: "Two" },
{ id: "3", name: "Three" },
{ id: "4", name: "Four" }
];
const handleActionClick = () => {
setActionIsOpen((prev) => !prev);
};
return (
<>
<div className="tw-relative">
<span onMouseDown={handleActionClick} className="tw-cursor-pointer">
<button onBlur={() => setActionIsOpen(false)}>Dropdown Click</button>
</span>
{actionIsOpen && (
<div className="shadow tw-w-48 tw-absolute tw-top-2 tw-z-50 tw-left-4 tw-bg-white tw-pt-2">
{actionList.map((val: any) => (
<div
key={val.id}
className="tw-bg-white-100 hover:tw-bg-violet-100 hover:tw-text-violet-900 tw-cursor-pointer hover:tw-font-bold py-2 px-3 tw-text-gray-600"
onMouseDown={() => alert(val.name)}
>
{val.name}
</div>
))}
</div>
)}
</div>
</>
);
};
export default Dropdown;
Something like this ?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论