React和Matchmedia

时间:2018-12-03 19:16:28

标签: javascript reactjs media-queries

我正在组件中使用react context API来安装设置方法。我还想在那里使用媒体查询,并设置一种根据屏幕尺寸打开或关闭sidenav的方法。

类似这样的东西

 componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath)

// Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
  const match = window.matchMedia(`(max-width: 768px)`) 
if(match {
context.setSidenavOpen(false)
  }
}

对于如何实现这样的目标感到困惑。我想调用该方法并将其设置在安装了组件的特定媒体断点处。这是使用反应路由器路径道具。因此,如果我点击了该组件提供的特定网址,并且屏幕尺寸如此,请关闭sidenav,否则将其保持打开状态。

2 个答案:

答案 0 :(得分:1)

您需要收听调整大小事件:

 componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath);

    // Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
    this.checkWidth = () => {
      const match = window.matchMedia(`(max-width: 768px)`);
      if (match) {
        context.setSidenavOpen(false);
      }
    };

    this.checkWidth();
    window.addEventListener("resize", this.checkWidth);
  }

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

或将侦听器添加到媒体查询本身:

componentDidMount() {
    let context = this.context;
    let path = this.props.pageContext && this.props.pageContext.path;
    context.setSidenavLeaf(newPath);

    // Below this is where I'd like to use the media query to set the sidenavOPen to false. Just not sure how to achieve that
    this.match = window.matchMedia(`(max-width: 768px)`);
    this.checkWidth = (e) => {      
      if (e.matches) {
        context.setSidenavOpen(false);
      }
    };

    this.checkWidth(this.match);
    this.match.addListener(this.checkWidth);
  }

  componentWillUnmount() {
    this.match.removeListener(this.checkWidth);
  }

答案 1 :(得分:0)

对于功能组件,github上有一个挂钩可以为您https://www.npmjs.com/package/react-simple-matchmedia