javascript - 如何使用反应删除组件卸载上的 div?
问题描述
我想使用 react 删除组件卸载时的 div 元素。
我在 usecallback 方法中创建了一个带有 id 门户的 div。我想在组件卸载时将其删除,我该怎么做。
下面是我的代码,
function Dialog () {
const [portal, setPortal] = React.useState<HTMLDivElement | null>(
(document.getElementById('portal') as HTMLDivElement) || null
);
const createPortalIfNotExists = React.useCallback(() => {
if (portal === null) {
const el = document.createElement('div');
el.id = 'portal';
document.body.appendChild(el);
setPortal(document.getElementById(
'portal'
) as HTMLDivElement);
}
}, [portal]);
createPortalIfNotExists();
if (portal === null) {
return null;
}
return ReactDOM.createPortal(
<>
<div>
{children}
</div>
</>,
portal
);
}
我在这里有两个问题,在这种情况下可以用 useEffect 代替 usecallback 。以及如何在组件卸载时删除带有 id 门户的 div。
有人可以帮我解决这个问题吗?
解决方案
通过使用 React.useEffect 内部返回方法,你可以做到。例如:
function Dialog () {
const [portal, setPortal] = React.useState<HTMLDivElement | null>(
(document.getElementById('portal') as HTMLDivElement) || null
);
const createPortalIfNotExists = React.useCallback(() => {
if (portal === null) {
const el = document.createElement('div');
el.id = 'portal';
document.body.appendChild(el);
setPortal(document.getElementById(
'portal'
) as HTMLDivElement);
}
}, [portal]);
React.useEffect(() => {
createPortalIfNotExists();
return () => {
const portalElement = portal || document.getElementById('portal')
portal.remove();
}
}, [])
if (portal === null) {
return null;
}
return ReactDOM.createPortal(
<>
<div>
{children}
</div>
</>,
portal
);
``
推荐阅读
- vim - 在 vim 命令行中移动
- python - OpenCV SVM,TypeError:不支持样本数据类型 = 17
- git - 为什么 git 命令失败
- amazon-web-services - 从正在运行的 AWS Glue 作业的上下文中使用 boto3 调用 AWS Glue 客户端 API 时,AWS Glue 作业挂起?
- ios - 在 UIBarButton 项中为自定义图像着色
- visual-studio - 来自引用项目的 Nuget Package dll 和文件夹未针对单击一次应用程序发布
- windows - 循环浏览 AHK 中所选单词的同义词
- office-js - 外部链接的 Office 加载项清单中不需要 AppDomains?
- scala - Flink - 产生运动不起作用
- php - php7如何检查,只有html形式的int值