获取对NextJs中任何组件的响应性道具

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

我的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 }
}

现在我可以访问将返回true或false的isMobile道具

const IndexPage = ({ isMobile }) => {
  return ( 
    <div>
     {isMobile ? (<h1>I am on mobile!</h1>) : (<h1>I am on desktop! </h1>)} 
    </div>
  )
}
reactjs next.js user-agent react-props
1个回答
1
投票

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

因此,如果您要使用isMobile道具进行响应式设计,实际上并没有帮助,因为在浏览器上,媒体查询是可以理解的,否则,您每次点击页面(SSR)时都可以检测到代理,并将其存储在类似redux的位置存储并在您的子组件中使用。

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

© www.soinside.com 2019 - 2024. All rights reserved.