簡體   English   中英

如何使用react刪除組件卸載上的div?

[英]How to remove a div on component unmount using react?

我想使用 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
   );
``

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM