我的NextJs应用程序中有一个检测userAgent的代码。这对NextJ页面来说是完全没有问题的。但是,当我需要将这个响应性的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 }
}
现在我可以访问
isMobile
道具,它将返回true或false
const IndexPage = ({ isMobile }) => {
return (
<div>
{isMobile ? (<h1>I am on mobile!</h1>) : (<h1>I am on desktop! </h1>)}
</div>
)
}
发布于 2020-04-26 10:19:01
这在您的组件中没有发生,因为它们将被呈现为客户端,但是每当您单击某个页面()时,请求头将被更新为当前代理。
因此,如果您要使用isMobile
道具进行响应性设计,这实际上是没有帮助的,因为在浏览器上,媒体查询是可以理解的,否则您可以在每次页面点击时检测到代理,并将其存储在类似redux的某个地方,然后在您的子组件中使用。
但是,例如,如果您单击页脚中的一个链接并呈现另一个组件--代理将不会被更新。
https://stackoverflow.com/questions/61436766
复制相似问题