如何在nextJS中将移动版代码与桌面版代码分开?

问题描述 投票:0回答:1

我正在使用 NextJS 进行一个项目,并且已经完成了桌面版本,当谈到移动版本时,我的客户不想要桌面版本的响应式布局,但他想要另一个完全不同的页面。例如,桌面版的主页内容对于移动用户来说是不一样的。

所以我的问题是:

  1. 如何检测用户代理然后返回有关用户正在使用的设备的特定页面?
  2. 我应该如何构建代码?我应该创建两个“src”文件夹,每个版本的代码一个?

提前致谢。

url-routing next.js13 adaptive-design
1个回答
2
投票

您可以使用库来检测用户是否来自移动设备或桌面 “移动检测”

// ------- 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>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.