本文介绍了如何使用Next.js在React SSR App上检测设备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Web应用程序上,我想显示两个不同的菜单,一个用于移动设备,一个用于桌面浏览器.我在服务器端呈现和库 react-device-detect .

on a web application I want to display two different Menu, one for the Mobile, one for the Desktop browser.I use Next.js application with server-side rendering and the library react-device-detect.

这是 CodeSandox链接.

import Link from "next/link";
import { BrowserView, MobileView } from "react-device-detect";

export default () => (
  <div>
    Hello World.{" "}
    <Link href="/about">
      <a>About</a>
    </Link>
    <BrowserView>
      <h1> This is rendered only in browser </h1>
    </BrowserView>
    <MobileView>
      <h1> This is rendered only on mobile </h1>
    </MobileView>
  </div>
);

如果您在浏览器中打开它并切换到移动视图并查看控制台,则会收到此错误:

If you open this in a browser and switch to mobile view and look the console you get this error:

之所以发生这种情况,是因为服务器的渲染检测到浏览器,并且在客户端上,他是移动设备.我发现的唯一解决方法是同时生成两者并使用CSS:

This happen because the rendering by the server detects a browser and on the client, he is a mobile device. The only workaround I found is to generate both and use the CSS like this:

.activeOnMobile {
  @media screen and (min-width: 800px) {
    display: none;
  }
}

.activeOnDesktop {
  @media screen and (max-width: 800px) {
    display: none;
  }
}

不是库,但是我真的不喜欢这种方法.有人知道在反应代码中直接处理SSR应用程序上的设备类型的良好做法吗?

Instead of the library but I don't really like this method. Does someone know the good practice to handle devices type on an SSR app directly in the react code?

推荐答案

我认为您应该通过在页面中使用getInitialProps来做到这一点,因为它同时在服务器和客户端上运行,并通过首先检测来获取设备类型如果您只是在获取网页请求(因此您仍在服务器上),或者正在重新渲染(因此您在客户端上).

I think you should do it by using getInitialProps in your page, as it runs both on the server and on the client, and getting the device type by first detecting if you are just getting the request for the webpage (so you are still on the server), or if you are re-rendering (so you are on the client).

// index.js

IndexPage.getInitialProps = ({ req }) => {
  let userAgent;
  if (req) { // if you are on the server and you get a 'req' property from your context
    userAgent = req.headers['user-agent'] // get the user-agent from the headers
  } else {
    userAgent = navigator.userAgent // if you are on the client you can access the navigator from the window object
  }
}

现在,您可以使用正则表达式查看设备是移动设备还是台式机.

Now you can use a regex to see if the device is a mobile or a desktop.

// still in getInitialProps

let isMobile = Boolean(userAgent.match(
  /Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile|WPDesktop/i
))

return { isMobile }

现在您可以访问isMobile道具,该道具将返回true或false

Now you can access the isMobile prop that will return either true or false

const IndexPage = ({ isMobile }) => {
  return (
    <div>
     {isMobile ? (<h1>I am on mobile!</h1>) : (<h1>I am on desktop! </h1>)}
    </div>
  )
}

我从本文获得希望对您有帮助

这篇关于如何使用Next.js在React SSR App上检测设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:54