next.js - 访问 NextJs 中函数组件外部获取的数据

标签 next.js

我有这段代码,我在其中导入一个名为颜色的常量,该常量包含我的项目所需的颜色:

import styled from 'styled-component';
import colors from '../utils/style/colors';

const Container = styled.div`
  background-colors:${colors.background}
`;

const BlogPage = () => {

  return (
    <Container>
      Main Contaienr
    </Container>
  );
};

export default BlogPage;

现在我想从数据库导入颜色。

我尝试了 getStaticProps,但无法在函数组件之外使用这些 props。

我的问题是如何获取数据并在函数组件外部使用它,即:在样式组件内部

最佳答案

您可以尝试使用ThemeProvider样式组件来解决这个问题。

  1. 通过 getStaticProps,我们将从数据库中获取数据(样式)。
  2. 使用 ThemeProvider 封装页面,并将数据从 getStaticProps 传递到提供程序。
  3. 现在,我们可以在组件中使用数据库中的样式。

pages/index.js

import { ThemeProvider } from 'styled-components';
import { BlogPage } from '../components/BlogPage.js';

export default function IndexPage({ theme }) {
  return (
    <ThemeProvider theme={theme}>
      <BlogPage />
    </ThemeProvider>
  );
}

export async function getStaticProps(context) {
  const databaseColors = {
    main: 'mediumseagreen',
    text: 'white',
  };

  return {
    props: {
      theme: databaseColors,
    },
  };
}

组件/BlogPage.js

import styled from 'styled-components';

const Container = styled.div`
  background-color:${({ theme }) => theme.main};
  color: ${(props) => props.theme.text};
`;

export const BlogPage = () => {
  return <Container>Main Contaienr</Container>;
};

export default BlogPage;

Edit dazziling-code

关于next.js - 访问 NextJs 中函数组件外部获取的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72606358/

相关文章:

javascript - NextJS - 导出被破坏(没有 CSS,没有 JS)

页面重新加载后 ReactJS 和 Next.js 404

reactjs - 在 Nextjs 中创建新门户时未定义文档

npm - Next.js 项目未启动

javascript - 下一个js : Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

reactjs - 如何在 _document 中添加自定义属性和扩展 DocumentInitialProps 类型?

javascript - Font-Awesome 添加了 aria-hidden 属性,可防止图标出现在浏览器中 [SSR]

javascript - React 服务器组件在 SEO 上的性能

reactjs - 如何在 react-quill 中注册对齐样式

javascript - 将 Next.js 链接插入 html 字符串