跳到主要内容

useClickOutside

监听元素外部的点击。 对于模式或下拉菜单很有用。

Usage

实时编辑器

function Demo() {
  const [visible, setVisible] = useState(false);

  const modalRef = useRef<HTMLDivElement>(null);

  useClickOutside(modalRef, () => {
    setVisible(false);
  });

  return (
    <div>
      <button onClick={() => setVisible(true)}> Open Modal</button>
      {visible && (
        <div
          ref={modalRef}
          style={{
            position: "fixed",
            left: "50%",
            top: "50%",
            transform: "translate(-50%,-50%)",
            width: 420,
            maxWidth: "100%",
            zIndex: 10,
            border: "1px solid var(--c-input-border)",
            background: "var(--c-bg)",
          }}
        >
          <div
            style={{
              padding: "0.4em 2em",
              boxShadow: "2px 2px 10px var(--c-box-shadow)",
            }}
          >
            <p
              style={{
                fontWeight: 700,
                fontSize: "1.4rem",
                marginBottom: "2rem",
              }}
            >
              Demo Modal
            </p>
            <p>Click outside of the modal to close it.</p>
          </div>
        </div>
      )}
    </div>
  );
}

结果
Loading...

API

useClickOutside

Returns

void

Arguments

参数名描述类型默认值
targetdom对象BasicTarget<Element> (必填)-
handler监听函数(evt: EventType) => void (必填)-
enabled监听函数是否生效boolean | undefined-

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;

EventType

export type EventType = MouseEvent | TouchEvent;