NodeJS 隐藏打印脚本外的div onclick,nextjs tailwindcss

ehxuflar  于 2023-03-01  发布在  Node.js
关注(0)|答案(1)|浏览(130)

我有一个modal,有typescript,next js和tailwindcss。我想在我点击modal之外的时候隐藏这个modal。但是我在tsx中得到了一些类型和其他错误。
在jsx中它工作的很好,但是在tsx中它不工作。如果有人帮助我,我将非常非常感谢。提前感谢

import { useRef, useEffect } from 'react';

const Backdrop = (props) => {

    const ref = useRef();
    const { onClick, children } = props;

    const handleClickOutside = (event) => {
        if (ref.current && !ref.current.contains(event.target)) {
            onClick && onClick();
        }
    };

    useEffect(() => {
        document.addEventListener("click", handleClickOutside, true);
        return () => {
            document.removeEventListener("click", handleClickOutside, true);
        };
    }, []);

    if (!children) {
        return null;
    }

    return (
        <div ref={ref}>
            {children}
        </div>
    );
}

export default Backdrop;
vbopmzt1

vbopmzt11#

使用IsClickOut.ts创建文件

复制此代码并粘贴

import { useEffect, useState, useCallback } from "react";

export const useIsClickOut = (setter: (bool: boolean) => void): [(node: any) => void] => {
    const [ele, setEle] = useState<HTMLDivElement | null>(null)
    const eleCallback = useCallback((node: HTMLDivElement) => { 
setEle(node) }, [])

useEffect(() => {
    if (ele === null) return;

    const handleClick = (e: any) => {
        if (ele.contains(e.target)) return;
        setter(false)
    }

    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
}, [ele]);

 return [eleCallback]
};

export default useIsClickOut;

在您的文件中介绍如何使用它

const [open, setOpen] = useState(false)
const [eleCallBack] = useIsClickOut(setOpen)
     
return !open ? null : (
   <div ref={eleCallBack}>
      {children}
   </div>
);

相关问题