fef*_*efe 5 state modal-dialog reactjs
我创建了一个自定义反应模式组件,我希望重构能够跟踪模式内容的外部点击并能够关闭模式我的代码如下所示。如果单击位于popup容器之外,我会寻找一种解决方法来删除创建门户,
import React from "react";
import ReactDOM from "react-dom";
const Hint = (props) => {
const ToggleContent = ({ toggle, content }) => {
const [isShown, setIsShown] = React.useState(false);
const hide = () => setIsShown(false);
const show = () => setIsShown(true);
return (
<React.Fragment>
{toggle(show)}
{isShown && content(hide)}
</React.Fragment>
);
};
const Modal = ({ children }) => {
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.body
);
};
return (
<div className={"hint"}>
<ToggleContent
toggle={(show) => (
<div className={"hint__icon"} onClick={show}>
{props.hintLabel ? (
<div className={"hint__label-text"}>{props.hintLabel}</div>
) : null}
</div>
)}
content={(hide) => (
<div className={"modal__body"}>
<Modal>
<div className={"popup"}>
<div className={"popup__wrapper"}>
<div
className={"popup__content"}
dangerouslySetInnerHTML={{ __html: props.content }}
></div>
</div>
<button onClick={hide} type="button" className="close">
X
</button>
</div>
</Modal>
</div>
)}
/>
</div>
);
};
ReactDOM.render(
<Hint hintLabel="test" content="teasasd ajsdghajsdg" />,
document.getElementById("app")
);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>Run Code Online (Sandbox Code Playgroud)
小智 6
我想,这个钩子可以帮助你。
export const useClickOutside = (
insideRefs,
isVisible,
onClose,
) => {
useEffect(() => {
const handleWindowClick = (event) => {
const someRefContainTarget = insideRefs
.filter((ref) => ref.current)
.some((ref) => ref.current.contains(event.target));
if (someRefContainTarget) {
return;
}
if (!isVisible) {
return;
}
if (onClose) {
onClose();
}
};
if (isVisible) {
window.addEventListener('click', handleWindowClick);
}
return () => {
if (isVisible) {
window.removeEventListener('click', handleWindowClick);
}
};
}, [isVisible, onClose]);
};
Run Code Online (Sandbox Code Playgroud)
只需传递所有内部onClose元素的-handler、visibility-state (在您的情况下)和 refs 即可。isShown
| 归档时间: |
|
| 查看次数: |
10634 次 |
| 最近记录: |