首页 > 解决方案 > 如何使用反应删除组件卸载上的 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。

有人可以帮我解决这个问题吗?

标签: javascriptreactjstypescript

解决方案


通过使用 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
   );
``

推荐阅读