跳到主要内容

useDocumentVisibility

跟踪 document.visibilityState 的 React Hook

Usage

实时编辑器

function Demo() {
  const visibility = useDocumentVisibility("hidden");
  const [message, setMessage] = useState(
    "💡 Minimize the page or switch tab then return",
  );

  useEffect(() => {
    if (visibility === "visible") {
      setTimeout(() => {
        setMessage("🎉 Welcome back!");
      }, 2000);
    }
    else {
      setTimeout(() => {
        setMessage("🥰 Take a break");
      }, 2000);
    }
  }, [visibility]);

  return <div>{message}</div>;
}

结果
Loading...

API

useDocumentVisiblity

Returns

DocumentVisibilityState: 文档可见性

Arguments

参数名描述类型默认值
defaultValue默认值DocumentVisibilityState | undefined-