【发布时间】:2019-11-10 06:53:57
【问题描述】:
在写这篇文章之前,我看到了this post,但我无法将所有代码链接到我的。
这是我的切换组件:
<ToggleContent
toggle={show => (
<div>
<button type="button" onClick={show} className={styles.acronym}>
{acronym}
</button>
</div>
)
}
content={show => (
<LogoutCard onClick={show} acronym={acronym} name={name} />
)}
/>
这是ToggleContent的内部
function ToggleContent({ toggle, content }) {
const [isShown, setIsShown] = useState(false);
const hide = () => setIsShown(false);
const show = () => setIsShown(!isShown);
return (
<Fragment>
{toggle(show)}
{isShown && content(hide)}
</Fragment>
);
}
这是 LogoutCard 在 props content 中的包装
import React, { useRef, useEffect } from "react";
/**
* Hook that alerts clicks outside of the passed ref
*/
function useOutsideAlerter(ref) {
/**
* Alert if clicked on outside of element
*/
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
useEffect(() => {
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
});
}
/**
* Component that alerts if you click outside of it
*/
export default function OutsideAlerter(props) {
const wrapperRef = useRef(null);
useOutsideAlerter(wrapperRef);
return <div ref={wrapperRef}>{props.children}</div>;
}
问题
问题是我可以打印警报,但我无法关闭弹出窗口,因为我无法传递 show 值,这是唯一允许关闭和打开的小弹出窗口。
问题
如何关闭弹出窗口?
【问题讨论】:
-
如果你能把它放在 jsFiddle 或 codeSandbox 之类的东西里会很好。
标签: javascript reactjs react-hooks