React监听浏览器窗口大小的改变
React监听浏览器窗口大小的改变
·
直接上干货
1.使用 react 函数时组件获取
import React, { useState, useEffect, } from 'react';
const App = () => {
// 浏览器的高度 默认设置为0;
const [height, setHeight] = useState(0);
const resizeUpdate = (e) => {
// 通过事件对象获取浏览器窗口的高度
let h = e.target.innerHeight;
setHeight(h);
};
useEffect(() => {
// 页面刚加载完成后获取浏览器窗口的大小
let h = window.innerHeight;
setHeight(h)
// 页面变化时获取浏览器窗口的大小
window.addEventListener('resize', resizeUpdate);
return () => {
// 组件销毁时移除监听事件
window.removeEventListener('resize', resizeUpdate);
}
}, []);
return (
<div>
浏览器的高度为:{height}
</div>
);
};
export default App;
2. 类式组件
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
height: 0
}
}
resizeUpdate = (e) => {
// 通过事件对象获取浏览器窗口高度
let h = e.target.innerHeight;
this.setState({height: h})
}
componentDidMount(){
// 页面加载完成获取高度
let h = window.innerHeight;
this.setState({height: h});
// 当页面大小改变后获取高度
window.addEventListener('resize', this.resizeUpdate);
}
componentWillUnmount(){
// 离开页面时移除监听事件
window.removeEventListener('resize', this.resizeUpdate);
}
render() {
return (
<div>
浏览器窗口的高度是:{this.state.height}
</div>
)
}
}
export default App;
更多推荐
已为社区贡献2条内容
所有评论(0)