[英]How to pass pageProps in next.js from a child component to _app.js?
I'm working on a next.js app and my page layout is going through the following hierarchy:我正在开发 next.js 应用程序,我的页面布局正在经历以下层次结构:
_app.js
Page.js
Header.js
PageContent.js
I need to pass some parameters from PageContent to Header without using redux.我需要在不使用 redux 的情况下将一些参数从 PageContent 传递给 Header。
Inside _app.js I have the following:在 _app.js 中,我有以下内容:
class Main extends App {
render() {
const {
Component,
pageProps,
apollo,
router: { route }
} = this.props;
return (
<ApolloProvider client={apollo}>
<Page
pathname={route.split("/")[1]}
{...pageProps}
localLinks={Component.LocalLinks}
render={props => <Component {...props} />}
/>
</ApolloProvider>
);
}
}
I'm assuming there should be a way to pass some propse (pageProps) from PageContent to _app and pass that down to Page and make them accessible to header.我假设应该有一种方法可以将一些 propse (pageProps) 从 PageContent 传递给 _app 并将其传递给 Page 并使它们可以被标题访问。 Is there a next.js specific trick here that I'm not familiar with?
这里有我不熟悉的 next.js 特定技巧吗?
Here's a full example with contexts (approach previously suggested in this other answer by slightly modifying https://github.com/vercel/next.js/tree/7df7c5e80515eea6745fd59e54d87e5ee709fe0c/examples/with-app-layout tested on Next.js 12.0.7 and React 17:这是一个带有上下文的完整示例(之前在这个其他答案中建议的方法通过稍微修改https://github.com/vercel/next.js/tree/7df7c5e80515eea6745fd59e54d87e5ee709fe0c/examples/with-app-layout在 Next.js 12.0.7 上测试和反应 17:
pages/_app.js页面/_app.js
import React from 'react'
export const MyAppContext = React.createContext({
n: 0,
setN: undefined,
});
function Header(props) {
return <div>n = { props.n }</div>
}
export default function App({ Component, pageProps }) {
const [n, setN] = React.useState(0)
return (
<MyAppContext.Provider value={{n, setN}}>
<Header n={n} />
<Component {...pageProps} />
</MyAppContext.Provider>
)
}
pages/index.js页面/index.js
import { MyAppContext } from './_app.js'
import React from 'react'
export default function Home() {
const {n, setN} = React.useContext(MyAppContext)
setN(new Date().getTime())
return <div>test</div>
}
If it's something that depends only on the page and not props如果它只取决于页面而不是道具
The following works without contexts, I wonder if setting such attributes could cause any problems down the line:以下在没有上下文的情况下工作,我想知道设置这些属性是否会导致任何问题:
pages/_app.js页面/_app.js
function Header(props) {
return <div>n = { props.n }</div>
}
export default function App({ Component, pageProps }) {
return (
<>
<Header n={Component.n} />
<Component {...pageProps} />
</>
)
}
pages/index.js页面/index.js
export default function Home() {
return <div>test</div>
}
Home.n = 1
You can use context api or Parent container state (here Page component).您可以使用上下文 api 或 Parent 容器状态(此处为 Page 组件)。
First Way -> Use context api第一种方式-> 使用上下文 api
Second Way第二种方式
** Third way ** **第三种方式**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.