reactjs - 如何使用反应钩子检测 Next.js SSR 中的窗口大小?
问题描述
我正在使用 Next.js 和react-dates构建一个应用程序。
我有两个组件DateRangePicker组件和DayPickerRangeController组件。
当窗口的宽度大于 1180px 时,我想渲染DateRangePicker,如果尺寸小于这个,我想渲染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)
}
}}
/>
}
我通常使用带有窗口对象的反应钩子来检测这样的窗口屏幕宽度
但是我发现这种方式在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;
}
推荐阅读
- shopify - Shopify购物车,如何知道req to change.js或update.js是否达到了产品的最大数量?
- python - 如何在 Python 中使嵌套循环更快更短
- json - 由 protojson 库生成的 JSON 中未显示 Protobuf 自定义选项
- amazon-web-services - 错误代码:AccessDeniedException。用户:arn:aws:iam::xxx:user/xxx 无权执行:lambda:CreateEventSourceMapping on resource:*
- laravel - 方法 Illuminate\Database\Eloquent\Collection::attach 在 laravel 8 中不存在错误
- python - 如何识别 Python 打开的 MySQL 中打开的连接
- sql - 如何在 .NET Core 的实体框架中的原始 SQL 中添加 CAST
- javascript - 在material-ui中为DatePicker添加自定义按钮
- opencv - 如何在 CUDA 内核中正确操作 CV_16SC3 Mat
- python - 根据当前时间和上次更新时间之间的小时计算时差