reactjs - 如何使用 react 钩子(Hook)检测 Next.js SSR 中的窗口大小?

标签 reactjs next.js server-side-rendering react-dates

我正在使用 Next.js 和 react-dates 构建应用程序.
我有两个组件 日期范围选择器 组件和 DayPickerRangeController 零件。
我要渲染 日期范围选择器 当窗口的宽度大于大小 1180px 时,如果大小小于这个我想渲染 DayPickerRangeController 反而。
这是代码:

      windowSize > 1180 ?
           <DateRangePicker
             startDatePlaceholderText="Start"
             startDate={startDate}
             startDateId="startDate"
             onDatesChange={handleOnDateChange}
             endDate={endDate}
             endDateId="endDate"
             focusedInput={focus}
             transitionDuration={0}
             onFocusChange={(focusedInput) => {
               if (!focusedInput) {
                 setFocus("startDate")
               } else {
                 setFocus(focusedInput)
                }
               }}
                /> :
             <DayPickerRangeController
               isOutsideRange={day => isInclusivelyBeforeDay(day, moment().add(-1, 'days'))}
               startDate={startDate}
               onDatesChange={handleOnDateChange}
               endDate={endDate}
               focusedInput={focus}
               onFocusChange={(focusedInput) => {
               if (!focusedInput) {
                 setFocus("startDate")
                 } else {
                  setFocus(focusedInput)
                 }
               }}
              /> 
          }
我通常使用带有窗口对象的 react 钩子(Hook)来检测窗口屏幕宽度,如 this
但是我发现这种方式在ssr的时候不可用,因为ssr渲染没有window对象。
无论ssr如何,有没有另一种方法可以安全地获取窗口大小?

最佳答案

您可以通过添加以下代码来避免在 ssr 中调用您的检测功能:

// make sure your function is being called in client side only
if (typeof window !== 'undefined') {
  // detect window screen width function
}
您的链接中的完整示例:
import { useState, useEffect } from 'react';

// Usage
function App() {
  const size = useWindowSize();

  return (
    <div>
      {size.width}px / {size.height}px
    </div>
  );
}

// Hook
function useWindowSize() {
  // Initialize state with undefined width/height so server and client renders match
  // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useEffect(() => {
    // only execute all the code below in client side
    if (typeof window !== 'undefined') {
      // Handler to call on window resize
      function handleResize() {
        // Set window width/height to state
        setWindowSize({
          width: window.innerWidth,
          height: window.innerHeight,
        });
      }
    
      // Add event listener
      window.addEventListener("resize", handleResize);
     
      // Call handler right away so state gets updated with initial window size
      handleResize();
    
      // Remove event listener on cleanup
      return () => window.removeEventListener("resize", handleResize);
    }
  }, []); // Empty array ensures that effect is only run on mount
  return windowSize;
}

关于reactjs - 如何使用 react 钩子(Hook)检测 Next.js SSR 中的窗口大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63406435/

相关文章:

javascript - React — 预期语法错误 : Unexpected token,;

javascript - 如何让 Next.js 和 redux-api 工作(使用 next-redux-wrapper)

javascript - Next.js 导入图片报错 Module parse failed : Unexpected character '�' (1:0)

Angular 通用 - TypeError : Converting circular structure to JSON

javascript - 将 Immutable.js map 列表转换为列表列表,然后将其用作谷歌图表的数据

javascript - 如何检查同一索引处的两个数组?

javascript - 输入元素在 React 中未更新

Azure Frontdoor 多路径路由不适用于存储静态 Web 应用程序

django - Django 在服务器端渲染 JS 吗?

javascript - Vue.js 服务器端渲染 : document is not defined