Reactjs 获得NextJs中任何组件的响应道具
我在我的NextJs应用程序中有一个检测用户代理的代码。这对于下一个TJS页面来说是完全可以的。但是,当我需要将此响应Reactjs 获得NextJs中任何组件的响应道具,reactjs,next.js,user-agent,react-props,Reactjs,Next.js,User Agent,React Props,我在我的NextJs应用程序中有一个检测用户代理的代码。这对于下一个TJS页面来说是完全可以的。但是,当我需要将此响应isMobileprop调用到组件(例如:页脚、页眉、导航)时,我应该怎么做 // index.js IndexPage.getInitialProps = ({ req }) => { let userAgent; if (req) { // if you are on the server and you get a 'req' property from y
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 }
}
现在我可以访问将返回true或false的isMobile
属性
constindexpage=({isMobile})=>{
报税表(
{isMobile?(我在手机上!):(我在桌面上!))
)
}
这不会发生在您的组件中,因为它们将呈现在客户端,但每当您点击页面(SSR)时,请求头将使用当前代理进行更新
因此,如果您打算使用isMobile
道具进行响应式设计,实际上是没有帮助的,因为在浏览器上,媒体查询是可以理解的,否则您可以在每次页面点击(SSR)时检测代理并将其存储在redux store之类的位置,然后在子组件中使用
但是,例如,如果您单击页脚中的链接并呈现另一个组件,则代理将不会更新。谢谢,Afsanefda。我可以将其存储在Next.js本身吗?当它是一个简单的Next.js应用程序,而我没有使用Redux时,您可以使用react context API在整个项目中存储和访问它。或者另一种不推荐的方法是将其存储在区域设置存储或cookie中(但要避免)
const IndexPage = ({ isMobile }) => {
return (
<div>
{isMobile ? (<h1>I am on mobile!</h1>) : (<h1>I am on desktop! </h1>)}
</div>
)
}