猿问

如何使用 useeffect react hook 在组件卸载时删除事件侦听器 mousedown?

我想使用下面的 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 在卸载时删除事件侦听器。我该怎么做 。有人可以帮我解决这个问题吗?谢谢。


蛊毒传说
浏览 170回答 1
1回答

largeQ

您removeEventListener()在清理功能中添加。您可以在文档中找到相关信息。React.useEffect(() => {&nbsp; &nbsp; const handleClickOutsideDialog = (event: any) => {&nbsp; &nbsp; &nbsp; &nbsp; if (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dialogRef &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; !dialogRef.contains(event.target)//error here&nbsp; &nbsp; &nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('You clicked outside of me!');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setIsDialogOpen(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; document.addEventListener('mousedown', handleClickOutsideDialog);&nbsp; &nbsp; return () => {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; document.removeEventListener('mousedown', handleClickOutsideDialog);&nbsp; &nbsp; }}, [setIsDialogOpen]);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答