react 如何自适应屏幕
React 实现自适应屏幕的方法
使用 CSS 媒体查询
通过 CSS 媒体查询可以根据不同屏幕尺寸应用不同的样式。在 React 中可以直接在组件样式文件或全局 CSS 中定义媒体查询规则。
@media (max-width: 768px) {
.container {
width: 100%;
padding: 10px;
}
}
使用 Flexbox 或 Grid 布局
Flexbox 和 Grid 布局可以自动调整元素大小和位置,适合构建响应式界面。
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
使用百分比或视口单位
使用百分比(%)或视口单位(vw、vh)可以让元素根据屏幕尺寸动态调整。
.box {
width: 50%;
height: 50vh;
}
使用 React 响应式 Hook
通过自定义 Hook 监听窗口尺寸变化,动态调整组件布局。
import { useState, useEffect } from 'react';
function useWindowSize() {
const [size, setSize] = useState([window.innerWidth, window.innerHeight]);
useEffect(() => {
const handleResize = () => {
setSize([window.innerWidth, window.innerHeight]);
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
function ResponsiveComponent() {
const [width] = useWindowSize();
return <div>{width < 768 ? 'Mobile' : 'Desktop'}</div>;
}
使用第三方库
一些第三方库如 react-responsive 或 react-sizeme 可以简化响应式开发。
import { useMediaQuery } from 'react-responsive';
function Example() {
const isMobile = useMediaQuery({ query: '(max-width: 768px)' });
return <div>{isMobile ? 'Mobile' : 'Desktop'}</div>;
}
动态加载组件
根据屏幕尺寸动态加载不同的组件,优化性能和用户体验。
const Component = React.lazy(() =>
window.innerWidth < 768
? import('./MobileComponent')
: import('./DesktopComponent')
);
图片和媒体适配
使用 srcset 或 picture 标签适配不同分辨率的图片。

<img
src="default.jpg"
srcSet="small.jpg 500w, medium.jpg 1000w, large.jpg 2000w"
sizes="(max-width: 600px) 500px, 1000px"
alt="Responsive"
/>
通过以上方法,可以轻松实现 React 应用的自适应屏幕需求。





