第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 useeffect react hook 在組件卸載時刪除事件偵聽器 mousedown?

如何使用 useeffect react hook 在組件卸載時刪除事件偵聽器 mousedown?

蠱毒傳說 2022-12-29 14:12:34
我想使用下面的 react usehook 刪除組件卸載上的 eventlistener mousedown 是我的代碼,function Dialog ({setIsDialogOpen, items}: Props) {const dialogRef = React.useRef<HTMLDivElement>(null);React.useEffect(() => {    const handleClickOutsideDialog = (event: any) => {        if (            dialogRef &&                !dialogRef.contains(event.target)//error here        ) {            alert('You clicked outside of me!');            setIsDialogOpen(false);          }    };    document.addEventListener('mousedown', handleClickOutsideDialog);}, [setIsDialogOpen]);return (    <Wrapper ref={dialogRef}>        <Container_one>            <span>title</span>            <Description> some big description</Description>        </Container_one>        <Container_two>            {items.map(item => (                <div                    key={item.id}                />            ))}        </Container_two>    </Wrapper>);這很好用。但我想使用 usehook 在卸載時刪除事件偵聽器。我該怎么做 。有人可以幫我解決這個問題嗎?謝謝。
查看完整描述

1 回答

?
largeQ

TA貢獻2039條經(jīng)驗 獲得超8個贊

您removeEventListener()在清理功能中添加。


您可以在文檔中找到相關(guān)信息。


React.useEffect(() => {

    const handleClickOutsideDialog = (event: any) => {

        if (

            dialogRef &&

                !dialogRef.contains(event.target)//error here

        ) {

            alert('You clicked outside of me!');

            setIsDialogOpen(false);

          }

    };

    document.addEventListener('mousedown', handleClickOutsideDialog);


    return () => { 

        document.removeEventListener('mousedown', handleClickOutsideDialog);

    }

}, [setIsDialogOpen]);


查看完整回答
反對 回復(fù) 2022-12-29
  • 1 回答
  • 0 關(guān)注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號