【发布时间】:2021-03-26 10:44:36
【问题描述】:
_app.js
function MyApp({ Component, pageProps }) {
return (
<Provider store={store}>
<Layout>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
Layout.js
function Layout({ children }) {
const [cartOpen, setCartOpen] = useState(false);
const handleOpen = () => setCartOpen(!cartOpen);
return (
<>
<Cart cartOpen={cartOpen} handleOpen={handleOpen} />
<main>{children}</main>
</>
)
}
ProductPage.js
function ProductPage(props) {
return (
<div>
<button onClick={() => console.log('set state to true in cartOpen(defined in layout.js)')}
</div>
)
}
在ProductPage 组件内部,它是Layout 的子组件,我希望一个元素有一个OnClick 事件处理程序,它将布局组件中的状态更改为setCartOpen(true)
【问题讨论】:
-
将
setCartOpen或函数作为道具传递给 ProductPage 并在 ProductPage 中调用该函数 -
或者您可以使用 React Context 使回调在
ProductPage中可用。
标签: reactjs next.js react-props react-state-management