简体   繁体   English

为什么反应中的匹配媒体无法正常工作?

[英]Why match media in react does not work properly?

Hey friends help me please,各位朋友请帮帮我

I am testing a media query in JavaScript and it doesn't work properly.我正在 JavaScript 中测试媒体查询,但它不能正常工作。 The condition is met with a measure before, for example:条件满足之前有一个度量,例如:

If it is min-with: 992px , the condition is met when the screen exceeds the width of 893px.如果是min-with: 992px ,则当屏幕超过 893px 的宽度时满足条件。

Why does this happen?为什么会这样? Working in vanilla JavaScript if it works perfectly.如果它完美运行,则在香草 JavaScript 中工作。

CODE代码

const mql = window.matchMedia("(min-width: 992px)");
   
    useEffect(() => {
      
        mql.addEventListener("change", resize);
        function resize(e) {
            if (e.matches) { // If media query matches
             
                console.log(window.screen.width);
               
            }
        }
        return () => {
            mql.removeEventListener("change", resize);
        }
    },[mql]);

CAPTURE捕获

在此处输入图像描述

This works.这行得通。 Tested 经过测试

  useEffect(() => {
      const mql = window.matchMedia("(min-width: 992px)");
      mql.addEventListener("change", resize);
      function resize(e) {
          if (e.matches) { // If media query matches
              console.log("more than 992");
          } else {
             console.log("less than 992")
          }
      }
      return () => {
          mql.removeEventListener("change", resize);
      }
  },[]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM