[英]React, return boolean value from custom hook
我有一個計算頁面高度和寬度的自定義鈎子,這個:
const [windowSize, setWindowSize] = useState({
height: 0,
width: 0
});
useEffect(() => {
const handleResize = () => {
setWindowSize({
height: window.innerHeight,
width: window.innerWidth
});
};
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
然后,在不同的組件中,我決定頁面何時是“移動的”或不是:
const isMobile: boolean = (useWindowSize().width <= 768);
然后在我的return
function 中,我使用isMobile
boolean 值來渲染或不渲染。
我的問題是,我怎么能擁有那個自定義鈎子,以便通過調用它來返回isMobile
值,換句話說,我想要類似的東西:
const isMobile: boolean = useIsMobile();
您可以在 state object 中添加額外的屬性:
const [windowSize, setWindowSize] = useState({
height: 0,
width: 0,
isMobile: false
});
並將其設置為:
setWindowSize({
height: window.innerHeight,
width: window.innerWidth,
isMobile: window.innerWidth <= 768
});
用法:
const {isMobile} = useWindowSize();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.