【问题标题】:React and MatchmediaReact 和 Matchmedia
【发布时间】:2019-05-05 03:21:18
【问题描述】:

我在组件中使用反应上下文 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)
  }
}

有点困惑如何实现这样的目标。我想调用该方法并将其设置在我的组件中的特定媒体断点处。哪个正在使用反应路由器路径道具。因此,如果我点击该组件呈现的特定 url 并且屏幕大小是这样的,请关闭 sidenav 否则将其保持打开状态。

【问题讨论】:

    标签: javascript reactjs media-queries


    【解决方案1】:

    你需要监听resize事件:

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

    【讨论】:

    • 不确定 API 是否在第一次回答后发生了变化,但 matchMedia 返回一个 MediaQueryList 对象而不是布尔值,因此这将始终通过检查。您需要测试 MediaQueryList.matches - Window.matchMedia()
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      相关资源
      最近更新 更多