📅  最后修改于: 2023-12-03 15:08:46.828000             🧑  作者: Mango
在 React 中获取窗口大小是一个比较常见的需求。下面介绍两种常用的方法。
可以使用 window 对象中的 innerWidth 和 innerHeight 属性获取当前窗口大小。想要在组件中获取窗口大小,可以在 componentDidMount 生命周期中添加监听器,在 componentWillUnmount 生命周期中移除监听器。
import React, { Component } from 'react';
class WindowSize extends Component {
constructor(props) {
super(props);
this.state = {
width: window.innerWidth,
height: window.innerHeight,
};
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleResize = () => {
this.setState({
width: window.innerWidth,
height: window.innerHeight,
});
};
render() {
const { width, height } = this.state;
return (
<div>
<p>Window width: {width}px</p>
<p>Window height: {height}px</p>
</div>
);
}
}
export default WindowSize;
使用 React Hooks 可以更简单地获取窗口大小。可以使用 useLayoutEffect 钩子函数在组件挂载时添加监听器,在组件卸载时移除监听器。
import React, { useState, useLayoutEffect } from 'react';
function useWindowSize() {
const [size, setSize] = useState([window.innerWidth, window.innerHeight]);
useLayoutEffect(() => {
function updateSize() {
setSize([window.innerWidth, window.innerHeight]);
}
window.addEventListener('resize', updateSize);
return () => window.removeEventListener('resize', updateSize);
}, []);
return size;
}
function WindowSize() {
const [width, height] = useWindowSize();
return (
<div>
<p>Window width: {width}px</p>
<p>Window height: {height}px</p>
</div>
);
}
export default WindowSize;
以上是两种在 React 中获取窗口大小的方法,使用哪种方法根据个人喜好和项目需求自行选择。