我使用的是nextjs(10.1.3
)。
I使用此功能:
import React, {useEffect, useState} from "react";
const useCheckMobileScreen = () => {
if (typeof window !== "undefined"){
const [width, setWidth] = useState(window.innerWidth);
const handleWindowSizeChange = () => {
setWidth(window.innerWidth);
}
useEffect(() => {
window.addEventListener('resize', handleWindowSizeChange);
return () => {
window.removeEventListener('resize', handleWindowSizeChange);
}
}, []);
return (width <= 768);
}
return false;
}
export default useCheckMobileScreen
现在我为布局调用这个函数:
import useCheckMobileScreen from "utiles/useCheckMobileScreen";
export const ProductItem = ({product}) => {
const isMobile = useCheckMobileScreen()
let itemClass = 'product-item';
if (isMobile) {
itemClass = itemClass + ' full-width'
}
return (
<div className={itemClass}>
...
但是当我的页面在第一次加载我的类'full-width'添加到我的元素。但当我刷新页面,'full-width'类名消失!
1条答案
按热度按时间9rbhqvlz1#
Just trigger the handler so that the state gets updated with initial window width.
Also, don't use
useEffect
anduseState
inside a conditional statement. Use a conditional statement inside the hook (but it can be done without even that in this case). Ref. Rule of HooksAnd you should consider reducing the 768px width (IMO that's the dimension of tablets).
CodeSandbox .
PS: This method only checks if viewport width is less than a certain constant, but that doesn't always mean that the user agent is a mobile browser. If you wish to achieve the latter you may consider using some library like
react-device-detect
. Moreover, seeing your provided example, I think you can do this more easily using CSS media queries.