react如何获取屏幕分辨率
获取屏幕分辨率的方法
在React中获取屏幕分辨率可以通过JavaScript的window对象实现。以下是几种常见的方法:
使用window.innerWidth和window.innerHeight
const screenWidth = window.innerWidth;
const screenHeight = window.innerHeight;
window.innerWidth和window.innerHeight返回浏览器视口的宽度和高度(包括滚动条)。

使用window.screen对象
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
window.screen.width和window.screen.height返回显示器的屏幕分辨率。

监听窗口大小变化
在React组件中,可以通过useEffect钩子监听窗口大小变化:
import React, { useState, useEffect } from 'react';
function ScreenResolution() {
const [resolution, setResolution] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setResolution({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<div>
<p>Width: {resolution.width}px</p>
<p>Height: {resolution.height}px</p>
</div>
);
}
使用自定义Hook
可以创建一个自定义Hook来复用屏幕分辨率逻辑:
import { useState, useEffect } from 'react';
function useScreenResolution() {
const [resolution, setResolution] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setResolution({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return resolution;
}
注意事项
window.screen返回的是显示器的物理分辨率,而window.innerWidth和window.innerHeight返回的是浏览器视口的大小。- 在服务器端渲染(SSR)时,
window对象不可用,需要做兼容处理。 - 移动设备可能有不同的像素密度,需要考虑设备像素比(
window.devicePixelRatio)。






