我正在使用 NextJS 进行一个项目,并且已经完成了桌面版本,当谈到移动版本时,我的客户不想要桌面版本的响应式布局,但他想要另一个完全不同的页面。例如,桌面版的主页内容对于移动用户来说是不一样的。
所以我的问题是:
提前致谢。
您可以使用库来检测用户是否来自移动设备或桌面 “移动检测”
// ------- Use the following code in your page folder -------
import MobileDetect from 'mobile-detect';
function checkIsMobile(context) {
const md = new MobileDetect(context.req.headers["user-agent"]);
return md.mobile() || md.tablet();
}
export const getServerSideProps = async context => {
const isMobile = checkIsMobile(context);
return {
props: {
isMobile
}
};
};
// ------- Create context for holding isMobile value -------
import { createContext } from 'react';
export const GlobalContext = createContext({
isMobile: false
});
export const GlobalContextProvider = ({ children, initialValue }) => {
return <GlobalContext.Provider value={initialValue}>
{children}
</GlobalContext.Provider>
}
// ------- _app file passing isMobile value to context -------
function App(props) {
const { Component, pageProps } = props;
return <>
<GlobalContextProvider initialValue={{
isMobile: pageProps.isMobile,
// you can pass here isAuth value
// is user authorised or not by checking it in getServerSideProps function
}}>
<Component {...pageProps} />
</GlobalContextProvider>
</>
}
// ------- hook for get value from context -------
import { useContext } from "react";
import { GlobalContext } from "...";
export const useIsMobile = () => {
const value = useContext(GlobalContext);
return value.isMobile;
};
// ------- Example component -------
const TestComponent = () => {
const isMobile = useIsMobile();
return (
<div>
{ isMobile ? 'Mobile version' : 'Desktop version' }
</div>
)
}