由于next.js分为在服务器渲染跟在客户端渲染,在服务器渲染是没法直接拿到navigator api,这时候要借助next.js的headers拿到客户端发起请求的请求头,它可以在next.js里面拿到.
首先从next/header中
'use server';
import { cookies, headers } from 'next/headers';
import { isMobileHandleByUserAgent } from 'src/utils/mobileHandle';
//获取请求头
const userAgent = headers().get('user-agent')
let isMobile = false;
if(userAgent){
isMobile= isMobileHandleByUserAgent(userAgent)
}
mobileHandle.ts文件示例代码 判断手机设备类型
export const isMobileHandle = () => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
);
}
export const isMobileHandleByUserAgent = (navigatorUserAgent:string) => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigatorUserAgent,
);
}
客户端组件屏幕判断可以直接获取,hooks封装示例代码如下:
import { useState, useEffect } from 'react';
import { isMobileHandle } from 'src/utils/mobileHandle';
export const useDeviceType = () => {
const [isMobile, setIsMobile] = useState(isMobileHandle())
useEffect(() => {
window.addEventListener('resize', () => {
setTimeout(() => {
setIsMobile(isMobileHandle());
}, 0);
});
return () => {
window.removeEventListener('resize', () => { });
};
}, [])
return { isMobile, setIsMobile }
}