How to detect if screen size has changed to mobile in React?

寵の児 提交于 2019-12-20 09:15:32

问题


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. 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.


回答1:


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});
}

EDIT: 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});
    }
}



回答2:


This is the same as @Ben Cohen answer but after attaching your function to eventListner, also remove it on componentWillUnmount

constructor() {
  super();
  this.state = { screenWidth: null };
  this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}

componentDidMount() {
    window.addEventListener("resize", this.updateWindowDimensions());
}

componentWillUnmount() {
    window.removeEventListener("resize", this.updateWindowDimensions)
}

updateWindowDimensions() {
   this.setState({ screenWidth: window.innerWidth });
}



回答3:


hey I just published a npm package for this issue. Check it out https://www.npmjs.com/package/react-getscreen

import React, { Component } from 'react';
import {withGetScreen} from 'react-getscreen'

class Test extends Component {
  render() {
    if (this.props.isMobile()) return <div>Mobile</div>;
    if (this.props.isTablet()) return <div>Tablet</div>;
    return <div>Desktop</div>;
  }
}

export default withGetScreen(Test);

//or you may set your own breakpoints by providing an options object

const options = {mobileLimit: 500, tabletLimit: 800}
export default withGetScreen(Test, options);


来源:https://stackoverflow.com/questions/44480053/how-to-detect-if-screen-size-has-changed-to-mobile-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!