【问题标题】:can't detect window width using hook无法使用钩子检测窗口宽度
【发布时间】:2022-02-02 14:12:05
【问题描述】:

我正在使用Gatsbyreact-hook/media-query 来检测窗口宽度的变化。

我认为它在大多数情况下都可以正常工作,但我通知它不能以奇怪的方式工作。

这是我所有媒体查询的自定义钩子。

import { useMediaQueries } from '@react-hook/media-query';

export default function useDetectDevice() {
  const { matchesAll: isMobile } = useMediaQueries({
    screen: 'screen',
    width: '(max-width: 640px)'
  });
  ...

  return {
    isMobile,
    ...
  };
}
const NewPage = () => {
  const { isMobile } = useDetectDevice();

  return (
    <h1 style={{isMobile ? '2.25rem' : '6rem'}}>test<h1>
  );
}

如果我通过 chrome 或任何网络浏览器更改窗口宽度,这将有效,但如果我重新启动页面,则无效。

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs media-queries gatsby


    【解决方案1】:

    SSR 似乎打破了最初的计算。尝试添加typeof window != 'undefined' 条件或使用useEffect 挂钩延迟一点初始计算,例如:

    import { useMediaQueries } from '@react-hook/media-query';
    
    export default function useDetectDevice() {
      if (typeof window != 'undefined'){
      const { matchesAll: isMobile } = useMediaQueries({
        screen: 'screen',
        width: '(max-width: 640px)'
      });
      ...
    
      return {
        isMobile,
        ...
      };
     }
    }
    

    当然,调整 sn-p 以使其工作,但要明白(定义一个空变量并将其填充到条件或类似内容中)。

    正如我所说,或者,您可以使用 useLayoutEffectuseEffect(带空的 deps,[])挂钩来触发计算,以确保 DOM 树已加载。

    相关问题:

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 2015-02-07
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多