获取对 NextJs 中任何组件的响应式道具
Get responsive props to any components in NextJs
我的 NextJs 应用程序中有一段代码可以检测 userAgent。这对于 NextJs 页面来说完全没问题。但是,当我需要将这个响应式 isMobile
prop 调用到组件(例如:页脚、页眉、导航)时,我应该怎么做?
// 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>
)
}
它不会在您的 组件中发生 因为它们将被呈现 client-side 但每当您点击页面 (SSR) 时,请求 header 将是使用当前代理更新。
因此,如果您打算使用 isMobile
道具进行响应式设计,它实际上没有帮助,因为在浏览器上媒体查询是可以理解的,否则您可以在每次页面点击时检测到您的代理 (SSR) 和将它存储在像 redux store 这样的地方,然后在你 child 组件中使用。
但是,例如,如果您单击页脚中的 link 并呈现另一个组件,代理将不会更新。
我的 NextJs 应用程序中有一段代码可以检测 userAgent。这对于 NextJs 页面来说完全没问题。但是,当我需要将这个响应式 isMobile
prop 调用到组件(例如:页脚、页眉、导航)时,我应该怎么做?
// 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>
)
}
它不会在您的 组件中发生 因为它们将被呈现 client-side 但每当您点击页面 (SSR) 时,请求 header 将是使用当前代理更新。
因此,如果您打算使用 isMobile
道具进行响应式设计,它实际上没有帮助,因为在浏览器上媒体查询是可以理解的,否则您可以在每次页面点击时检测到您的代理 (SSR) 和将它存储在像 redux store 这样的地方,然后在你 child 组件中使用。
但是,例如,如果您单击页脚中的 link 并呈现另一个组件,代理将不会更新。