当前位置:首页 > React

react如何检测窗口

2026-01-14 10:50:43React

监听窗口大小变化

使用useEffect钩子和resize事件监听窗口尺寸变化。在组件挂载时添加事件监听器,卸载时移除监听器以避免内存泄漏。

import { useState, useEffect } from 'react';

function WindowSizeDetector() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div>
      Window width: {windowSize.width}, height: {windowSize.height}
    </div>
  );
}

自定义Hook封装

将窗口检测逻辑封装成可复用的自定义Hook,便于在多个组件中使用。

react如何检测窗口

import { useState, useEffect } from 'react';

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowSize;
}

// 使用示例
function ResponsiveComponent() {
  const { width } = useWindowSize();
  const isMobile = width < 768;

  return (
    <div>{isMobile ? 'Mobile View' : 'Desktop View'}</div>
  );
}

性能优化

对于频繁触发的resize事件,使用防抖(debounce)或节流(throttle)技术减少事件处理频率,避免性能问题。

react如何检测窗口

import { useState, useEffect } from 'react';
import { throttle } from 'lodash';

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = throttle(() => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    }, 200);

    window.addEventListener('resize', handleResize);
    return () => {
      handleResize.cancel();
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return windowSize;
}

检测窗口滚动位置

监听窗口滚动事件,获取当前滚动位置信息,可用于实现滚动加载或视差效果。

import { useState, useEffect } from 'react';

function useScrollPosition() {
  const [scrollPosition, setScrollPosition] = useState({
    x: window.pageXOffset,
    y: window.pageYOffset
  });

  useEffect(() => {
    const handleScroll = () => {
      setScrollPosition({
        x: window.pageXOffset,
        y: window.pageYOffset
      });
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return scrollPosition;
}

浏览器可见性检测

通过visibilitychange事件检测当前标签页是否可见,适用于需要暂停后台任务的场景。

import { useState, useEffect } from 'react';

function usePageVisibility() {
  const [isVisible, setIsVisible] = useState(!document.hidden);

  useEffect(() => {
    const handleVisibilityChange = () => {
      setIsVisible(!document.hidden);
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  return isVisible;
}

标签: 窗口react
分享给朋友:

相关文章

react如何读

react如何读

React 的发音 React 的发音为 /riˈækt/(音标),读作“瑞-艾克特”。其中: “Re” 发音类似英文单词 “read” 的开头部分。 “act” 发音与英文单词 “act” 一致…

react如何发布

react如何发布

发布React应用的步骤 构建生产版本 使用以下命令生成优化后的生产版本代码,代码会被压缩并移除开发环境中的调试工具: npm run build 构建完成后会生成build文件夹,包含所有静态资源…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…

react如何重启

react如何重启

重启 React 应用的方法 重新加载当前页面 使用 window.location.reload() 强制刷新页面,这会重新加载整个应用并重置所有状态。 window.location…

react如何通信

react如何通信

React 组件通信方式 React 组件间的通信方式多样,具体选择取决于组件关系和场景需求。以下是常见方法: 父子组件通信 父组件通过 props 向子组件传递数据,子组件通过回调函数通知父…

java如何react

java如何react

在Java中使用React 要在Java项目中集成React,通常需要将React前端与Java后端结合使用。以下是几种常见的方法: 使用Spring Boot作为后端 Spring Boot是一个…