Next.js 提升状态

Next.js Lifting state up

_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>
    )
}

在作为 Layout 的子组件的 ProductPage 组件内,我希望元素具有 OnClick 事件处理程序,它将布局组件中的状态更改为 setCartOpen(true)

Link to sandbox

您可以利用 React 上下文使 setCartOpen 可用于树下的任何组件。

import React, { createContext, useState } from 'react';

export const CartContext = createContext(null);

function Layout({ children }) {
    const [cartOpen, setCartOpen] = useState(false);
    const handleOpen = () => setCartOpen(!cartOpen);

    return (
        <CartContext.Provider value={{ cartOpen, setCartOpen }}>
            <Cart cartOpen={cartOpen} handleOpen={handleOpen} />
            <main>{children}</main>
        </CartContext.Provider>  
    )
}

export default Layout;

然后,在您的页面中,只需从上下文中检索 setCartOpen 并使用它。

import { CartContext } from '<your-path-to>/Layout';

function ProductPage(props) {
    const { setCartOpen } = useContext(CartContext);

    return (
        <div>
            <button onClick={() => setCartOpen(true)}>Open Cart</button>
        </div>
    );
}

export default ProductPage;