reactjs - 带有 React Hooks 的多模态
问题描述
我正在构建一些有趣的模态,但我不能让它适用于多个模态。
使用模态钩子
import { useState } from 'react';
const useModal = () => {
const [isShowing, setIsShowing] = useState(false);
const toggle = () => {
setIsShowing(!isShowing);
}
return {
isShowing,
toggle,
}
};
export default useModal;
模态组件
import React, { useEffect } from 'react';
const Modal = (props) => {
const { toggle, isShowing, children } = props;
useEffect(() => {
const handleEsc = (event) => {
if (event.key === 'Escape') {
toggle()
}
};
if (isShowing) {
window.addEventListener('keydown', handleEsc);
}
return () => window.removeEventListener('keydown', handleEsc);
}, [isShowing, toggle]);
if (!isShowing) {
return null;
}
return (
<div className="modal">
<button onClick={ toggle } >close</button>
{ children }
</div>
)
}
export default Modal
在我的主要组件中
如果我这样做,页面中唯一的模式可以正常工作
const { isShowing, toggle } = useModal();
...
<Modal isShowing={ isShowing } toggle={ toggle }>first modal</Modal>
但是当我尝试添加另一个时它不起作用。它没有打开任何模式
const { isShowingModal1, toggleModal1 } = useModal();
const { isShowingModal2, toggleModal2 } = useModal();
...
<Modal isShowing={ isShowingModal1 } toggle={ toggleModal1 }>first modal</Modal>
<Modal isShowing={ isShowingModal2 } toggle={ toggleModal2 }>second modal</Modal>
我做错了什么?谢谢你
如果您想查看它,请转到https://codesandbox.io/s/hopeful-cannon-guptw?fontsize=14&hidenavigation=1&theme=dark
解决方案
试试看:
const useModal = () => {
const [isShowing, setIsShowing] = useState(false);
const toggle = () => {
setIsShowing(!isShowing);
};
return [isShowing, toggle];
};
然后:
export default function App() {
const [isShowing, toggle] = useModal();
const [isShowingModal1, toggleModal1] = useModal();
const [isShowingModal2, toggleModal2] = useModal();
推荐阅读
- c# - 如何从 Process.ExitCode 检查 git pull 是否成功
- python - 在python3中检测到输入之前如何做某事?
- android - Firebase 动态链接分析如何捕获 APP_INSTALL/APP_FIRST_OPEN 等事件?
- css - 忽略 style.css 的更新(新版本已上线,缓存已清除)
- javascript - javascript 新手并尝试使用 setTimeout
- python - 为什么 numpy.resize 不适用于像 numpy.reshape 这样的“-1”?
- python - 比较两个数据帧的值
- mysql - Mysql 计算多个 SUM() 变量
- python - 有没有办法使用 Sphinx (autodoc) 显示 Snakefile 的文档字符串?
- java - 选择按钮的 Xpath