我有一个组件需要侦听窗口调整大小,并适当地隐藏/显示侧边栏。 我决定为此创建一个自定义钩子,但似乎无法正常工作。
主要问题是mainSidebar
值始终是常数,并且更新未正确读取。
这是钩子本身:
export function useResizeListener(cb: (this: Window, e: UIEvent) => any) {
const [size, setSize] = React.useState({ width: window.outerWidth, height: window.outerHeight })
React.useEffect(() => {
function _wrapped(this: Window, e: UIEvent): any {
console.debug('setting size and calling callback', { width: this.outerWidth, height: this.outerHeight })
setSize({ width: this.outerWidth, height: this.outerHeight })
cb.call(this, e)
}
window.addEventListener('resize', _wrapped)
return () => window.removeEventListener('resize', _wrapped)
}, [size.width, size.height])
}
这是使用它的组件:
const shouldHaveSidebar = () => document.body.clientWidth >= ScreenSizes.Tablet
const HomePage: React.FunctionComponent<IProps> = (props) => {
const [mainSidebar, toggleMainSidebar] = React.useState(shouldHaveSidebar())
useResizeListener(() => {
console.debug('device width vs tablet width:', document.body.clientWidth, '>=', ScreenSizes.Tablet)
console.debug('shouldHaveSidebar vs mainSidebar', shouldHaveSidebar(), '!==', mainSidebar)
if (shouldHaveSidebar() !== mainSidebar) {
console.debug('setting to', shouldHaveSidebar())
toggleMainSidebar(shouldHaveSidebar())
}
})
return ...
}
在Chrome开发者检查器设备模式下切换视口大小时,我会在控制台中获得此输出。请注意,我从台式机开始,然后更改为移动L。
setting size and calling callback {width: 1680, height: 1027}
device width vs tablet width: 1146 >= 800
shouldHaveSidebar vs mainSidebar true !== false
setting to true
setting size and calling callback {width: 425, height: 779}
device width vs tablet width: 425 >= 800
shouldHaveSidebar vs mainSidebar false !== false // <--- should be: false !== true
_wrapper
钩子的内部和外部之间移动useEffect
函数这些都不起作用。
我在做什么错了?
答案 0 :(得分:1)
我建议重组解决方案。首先,我将useResizeListener
更改为一个可提供窗口大小的钩子:
export function useWindowSize() {
const [size, setSize] = React.useState({ width: window.clientWidth, height: window.clientHeight });
React.useEffect(() => {
function handleResize(e: UIEvent) {
setSize({ width: window.clientWidth, height: window.clientHeight });
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
然后在您的HomePage
组件中:
const shouldHaveSidebar = (size) => size.width >= ScreenSizes.Tablet
const HomePage: React.FunctionComponent<IProps> = (props) => {
const size = useWindowSize();
const mainSidebar = shouldHaveSidebar(size);
// Now if you want to perform an action when the size changes you cna simply do:
useEffect(() => {
// Perform your action here
}, [size.width, size.height]);
// ...
}