如何在 React 中检测屏幕尺寸是否已更改为移动设备? [英] How to detect if screen size has changed to mobile in React?
问题描述
我正在使用 React 开发 Web 应用程序,需要检测屏幕尺寸何时进入移动断点以更改状态.
I am developing a web app with React and need to detect when the screen size has entered the mobile break-point in order to change the state.
特别是当用户进入移动模式时,我需要折叠我的 sidenav,这由存储在组件内状态中的布尔值控制.
Specifically I need my sidenav to be collapsed when the user enters mobile mode and that is controlled with a boolean stored in the state within the component.
推荐答案
我所做的是在组件挂载后添加一个事件监听器:
What I did is adding an event listener after component mount:
componentDidMount() {
window.addEventListener("resize", this.resize.bind(this));
this.resize();
}
resize() {
this.setState({hideNav: window.innerWidth <= 760});
}
componentWillUnmount() {
window.removeEventListener("resize", this.resize.bind(this));
}
为了保存状态更新,我更改了调整大小"有点,只在窗口宽度发生变化时更新.
To save state updates, I changed the "resize" a bit, just to be updated only when there is a change in the window width.
resize() {
let currentHideNav = (window.innerWidth <= 760);
if (currentHideNav !== this.state.hideNav) {
this.setState({hideNav: currentHideNav});
}
}
更新:是时候使用钩子了!如果你的组件是功能性的,并且你使用了钩子 - 那么你可以使用 useMediaQuery
钩子,来自 react-responsive
包.
UPDATE: Time to use hooks!
If you're component is functional, and you use hooks - then you can use the useMediaQuery
hook, from react-responsive
package.
import { useMediaQuery } from 'react-responsive';
...
const isMobile = useMediaQuery({ query: `(max-width: 760px)` });
使用这个钩子后,isMobile"将在屏幕调整大小时更新,并将重新渲染组件.好多了!
After using this hook, "isMobile" will be update upon screen resize, and will re-render the component. Much nicer!
这篇关于如何在 React 中检测屏幕尺寸是否已更改为移动设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!