从其嵌套组件更改主布局颜色

问题描述 投票:0回答:1

我有 next.js 应用程序,当前主要布局有

mainColor
#fff.

我希望能够从

TestComponent
组件更改颜色。我需要为此求助于全局状态管理工具吗?

const TestPage = () => {
  return <TestComponent />;
};

TestPage.getLayout = (page: ReactElement) => {
  return <MainLayout mainColor="#fff">{page}</MainLayout>;
};

export default TestPage;
next.js next
1个回答
0
投票

要从 Next.js 中的

mainColor
组件更改
MainLayout
组件的
TestComponent
属性,您可以使用 React Context。这样,您可以避免使用全局状态管理工具,并且仍然可以轻松地在 Next.js 中的组件之间传递数据。以下是您如何实现这一目标:

  1. 在单独的文件中创建一个新的上下文(我们称之为 themeContext.js):
import { createContext } from "react";

const defaultTheme = {
  mainColor: "#fff"
};

const ThemeContext = createContext(defaultTheme);

export default ThemeContext;
  1. 使用 ThemeContext 提供程序包装
    MainLayout
    组件
    TestPage
    成分:
import ThemeContext from "./themeContext.js";

const TestPage = () => {
  const theme = {
    mainColor: "#fff"
  };
  
  return (
    <ThemeContext.Provider value={theme}>
      <TestComponent />;
    </ThemeContext.Provider>
  );
};

TestPage.getLayout = (page: ReactElement) => {
  return <MainLayout mainColor="#fff">{page}</MainLayout>;
};

export default TestPage;
  1. MainLayout
    组件中,从 主题背景:
import { useContext } from "react";
import ThemeContext from "../themeContext.js";

const MainLayout = ({ children }) => {
  const { mainColor } = useContext(ThemeContext);

  return (
    <div style={{ backgroundColor: mainColor }}>
      {children}
    </div>
  );
};

export default MainLayout;

现在,在 TestComponent 组件中,您可以通过更新

TestPage
组件中的主题对象来更改 mainColor 属性:

import { useContext } from "react";
import ThemeContext from "./themeContext.js";

const TestComponent = () => {
  const { mainColor } = useContext(ThemeContext);

  return <div style={{ backgroundColor: mainColor }}>Test Component</div>;
};

export default TestComponent;
© www.soinside.com 2019 - 2024. All rights reserved.