簡體   English   中英

如何使用 NextJS 檢測移動設備

[英]How to detect mobile device with NextJS

有很多主題和SO問題。 但我沒有找到檢測移動設備的最佳解決方案。

我有兩個組成部分。 第一個組件僅適用於桌面,第二個組件僅適用於手機。

{isMobile? 
(<SecondComponent />) 
: 
(<FirstComponent />)
}

大多數解決方案使用getInitialProps function。但是 Nextjs 說:

Recommended: getStaticProps or getServerSideProps

關聯

你使用這樣的東西:

export const isMobileDevice = () => /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

簡單的方法是讓瀏覽器用 matchMedia告訴你:

let isMobile = window.matchMedia("(max-width: 600px)").matches;

我沒試過這個,但這篇文章建議使用req.device 所以你可能會做這樣的事情

export async function getServerSideProps(context) {
 
  return {
    props: {
      device: context.req.device,
    },
  }
}

編輯:您需要安裝express-device

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM