reactjs 如何知道代理是否为移动的设备- nextjs

tquggr8v  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(110)

我使用的是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'类名消失!

9rbhqvlz

9rbhqvlz1#

Just trigger the handler so that the state gets updated with initial window width.
Also, don't use useEffect and useState 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 Hooks
And you should consider reducing the 768px width (IMO that's the dimension of tablets).

import { useState, useEffect } from "react";

const useCheckMobileScreen = () => {
  const [width, setWidth] = useState(0);

  useEffect(() => {
    const handleWindowSizeChange = () => setWidth(window.innerWidth);
    handleWindowSizeChange();
    window.addEventListener("resize", handleWindowSizeChange);
    return () => window.removeEventListener("resize", handleWindowSizeChange);
  }, []);

  return width <= 576;
};

export default useCheckMobileScreen;

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.

相关问题