我正在使用 Next.js 构建一个应用程序反应日期 https://github.com/airbnb/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)
}
}}
/>
}
我通常使用带有窗口对象的反应钩子来检测窗口屏幕宽度,例如this https://usehooks.com/useWindowSize/
但我发现这种方式在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
// 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;
}
注意:更新为 Sergey Dubovik 评论,我们不需要验证窗口,因为 useEffect 在客户端运行
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)