reactjs - 获取 NextJs 中任何组件的响应式 props

标签 reactjs next.js user-agent react-props

我的 NextJs 应用程序中有一段代码用于检测 userAgent。这对于 NextJs 页面来说完全没问题。但是,当我需要向组件(例如:页脚、页眉、导航)调用此响应式 isMobile 属性时,我应该做什么?

// 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
  }

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

  return { isMobile }
}

Now I 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>
  )
}

最佳答案

这不会发生在您的组件中,因为它们将在客户端呈现,但每当您点击页面(SSR)时,请求 header 都会使用当前代理进行更新。

因此,如果您打算使用 isMobile 属性进行响应式设计,它实际上没有帮助,因为在浏览器上媒体查询是可以理解的,否则每次页面点击时您都可以检测到您的代理(SSR)并将其存储在像 redux store 这样的地方,然后在您的子组件中使用。

但是,例如,如果您单击页脚中的链接并呈现另一个组件,则代理将不会更新。

关于reactjs - 获取 NextJs 中任何组件的响应式 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61436766/

相关文章:

html - 带 CSS 网格的水平滚动

http - 路径中的非法字符取决于用户代理?

ReactJS如何循环动态命名的引用

javascript - 为什么我会收到意外的模板字符串表达式错误?

reactjs - Next.js + React 返回上一页

javascript - 在 NextJS 中使用 useContext 和 useReducer 并读取 null 作为上下文

google-chrome - 什么 Accept-CH 值等同于用于识别浏览器的 User-Agent?

javascript - 在 javascript 中检测 Mountain Lion (OS X 10.8)?

javascript - 索环:顶部和底部选项卡激活相同的内容

reactjs - React 按钮 onClick 需要两次单击才能第二次工作