[英]Can I use the '<Component {…pageProps} />' that I usually found in _app.js in Next.js for React.js
[英]How to pass pageProps in next.js from a child component to _app.js?
我正在開發 next.js 應用程序,我的頁面布局正在經歷以下層次結構:
_app.js
Page.js
Header.js
PageContent.js
我需要在不使用 redux 的情況下將一些參數從 PageContent 傳遞給 Header。
在 _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>
);
}
}
我假設應該有一種方法可以將一些 propse (pageProps) 從 PageContent 傳遞給 _app 並將其傳遞給 Page 並使它們可以被標題訪問。 這里有我不熟悉的 next.js 特定技巧嗎?
這是一個帶有上下文的完整示例(之前在這個其他答案中建議的方法通過稍微修改https://github.com/vercel/next.js/tree/7df7c5e80515eea6745fd59e54d87e5ee709fe0c/examples/with-app-layout在 Next.js 12.0.7 上測試和反應 17:
頁面/_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>
)
}
頁面/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>
}
如果它只取決於頁面而不是道具
以下在沒有上下文的情況下工作,我想知道設置這些屬性是否會導致任何問題:
頁面/_app.js
function Header(props) {
return <div>n = { props.n }</div>
}
export default function App({ Component, pageProps }) {
return (
<>
<Header n={Component.n} />
<Component {...pageProps} />
</>
)
}
頁面/index.js
export default function Home() {
return <div>test</div>
}
Home.n = 1
您可以使用上下文 api 或 Parent 容器狀態(此處為 Page 組件)。
第一種方式-> 使用上下文 api
第二種方式
**第三種方式**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.