
使用React Hooks:
您可以定义一个自定义的Hook来监听window
resize事件,如下所示:
import React, { useLayoutEffect, useState } from 'react';function useWindowSize() { const [size, setSize] = useState([0, 0]); useLayoutEffect(() => { function updateSize() { setSize([window.innerWidth, window.innerHeight]); } window.addEventListener('resize', updateSize); updateSize(); return () => window.removeEventListener('resize', updateSize); }, []); return size;}function ShowWindowDimensions(props) { const [width, height] = useWindowSize(); return <span>Window size: {width} x {height}</span>;}这样做的好处是逻辑被封装,您可以在要使用窗口大小的任何位置使用此Hook。
使用React类:
您可以在componentDidMount中进行监听,类似于该组件,它仅显示窗口尺寸(如
<span>Window size: 1024 x768</span>):
import React from 'react';class ShowWindowDimensions extends React.Component { state = { width: 0, height: 0 }; render() { return <span>Window size: {this.state.width} x {this.state.height}</span>; } updateDimensions = () => { this.setState({ width: window.innerWidth, height: window.innerHeight }); }; componentDidMount() { window.addEventListener('resize', this.updateDimensions); } componentWillUnmount() { window.removeEventListener('resize', this.updateDimensions); }}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)