英文:
How to click on anchor tags inside React dropdown
问题
我在同一页中有一个下拉菜单,需要在多个地方使用它。
我的问题是:在打开任何下拉菜单后,我无法单击下拉菜单链接。当我尝试单击时,下拉菜单会消失。
英文:
I have a dropdown & I need to use this dropdown multiple places in same page.
My issue: after open any dropdown I'm not able to click on dropdown links. When I'm trying to click then dropdown is disappearing.
答案1
得分: 2
请查看 https://stackoverflow.com/questions/17769005/onclick-and-onblur-ordering-issue/57630197#57630197
在 a
组件上添加 onMouseDown
事件,并调用 e.preventDefault()
。
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 onClick={handleActionClick} onBlur={() => setActionIsOpen(false)} className="tw-cursor-pointer">
<button>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">
<a href="#" onMouseDown={(e) => e.preventDefault()}>
{val.name}
</a>
</div>
))}
</div>
)}
</div>
</>
);
};
export default Dropdown;
英文:
See https://stackoverflow.com/questions/17769005/onclick-and-onblur-ordering-issue/57630197#57630197
Add the onMouseDown
event on the a
component and call e.preventDefault()
.
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 onClick={handleActionClick} onBlur={() => setActionIsOpen(false)} className="tw-cursor-pointer">
<button>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">
<a href="#" onMouseDown={(e) => e.preventDefault()}>
{val.name}
</a>
</div>
))}
</div>
)}
</div>
</>
);
};
export default Dropdown;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论