【发布时间】:2021-11-19 21:45:33
【问题描述】:
我有一个简单的 Modal 组件和一个简单的 Tooltip 组件。两者都可以通过点击触发按钮打开并通过点击外部关闭。为了检测外部点击,我使用了这个简单的钩子:
const useClickAway = (
ref: Ref,
condition: boolean,
handler: Handler
): void => {
useEffect(() => {
const listener = (e: Event) => {
if (!ref.current || ref.current.contains(e.target as Node)) {
return;
}
handler(e);
};
if (condition) {
document.addEventListener('mouseup', listener);
document.addEventListener('touchend', listener);
}
return () => {
document.removeEventListener('mouseup', listener);
document.removeEventListener('touchend', listener);
};
}, [ref, handler, condition]);
};
这就是我使用它的方式:
/*
* ref - reference to the modal container
* isOpen - The modal state.
* handleClose - Handler that closes the modal.
*/
useClickAway(ref, isOpen, handleClose)
到目前为止它工作正常,但是当我尝试在此 Modal 内渲染我的工具提示(使用 Portal 将其渲染到 body 元素中,而不是反应树)时出现了问题。
当我打开模态然后打开其中的工具提示时,单击工具提示会导致模态关闭。因为点击工具提示被认为是点击了模态框的外部。
谁能为这个问题提供干净的解决方案?
【问题讨论】:
标签: reactjs modal-dialog click tooltip portal