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