如何在 React 中创建一个点击外部区域(模块)时关闭的弹出菜单?
由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!
所以,你想在网站上添加一个弹出窗口,却找不到合适的教程。别担心,你友好的 React 开发者邻居来帮你解决这个问题了。
首先,我们将使用一个外部 npm 模块来简化操作。
yarn add react-click-away-listener
或者
npm i react-click-away-listener
接下来,我们来看语法:
您可以在这里找到更多文档:链接
import { useState ) from 'react';
import ClickAwayListener from 'react-click-away-listener';
const App = () => {
const [popup, setPopup] = useState(false)
return (
{/* The option to open the popup */}
<button onClick={() => setPopup(true)}>Click Me</button>
{/* The popup itself */}
{popup && (
<ClickAwayListener onClickAway={() => setPopup(false)}>
<div className={'popup'}>
<li>Items of the Popup</li>
<li>Items of the Popup</li>
<li>Items of the Popup</li>
</div>
</ClickAwayListener>
)}
)
};
好了,以上就是如何在 React 中创建一个点击即可打开的监听弹窗的基本方法。本文暂不涉及样式部分,但我很快会专门写一篇。
文章来源:https://dev.to/kunal/how-to-create-a-popup-menu-in-react-34hh