首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在全局样式组件中使用ThemeProvider道具

在全局样式组件中使用ThemeProvider道具
EN

Stack Overflow用户
提问于 2018-05-28 06:20:11
回答 2查看 3.9K关注 0票数 4

如何在使用ThemeProvider props时访问global.js中的造型-部件

例如,在theme.js中,${props => props.theme.fonts.fontSize}调用默认字体大小为16px

代码语言:javascript
复制
const theme = {
    fonts: {
        fontSize : '16px',
    }
}

export default theme

这是在/layouts/index.js中提供的

代码语言:javascript
复制
import React from 'react'

import { ThemeProvider } from 'styled-components'
import '../style/global';
import theme from '../style/theme'

class Template extends React.Component {
  render() {
    const { children } = this.props

    return (
      <ThemeProvider theme={theme}>
        ...
        {children()}
        ...
      </ThemeProvider>
    )
  }
}

export default Template

从这里开始,我可以访问每个组件或子页面中的${props => props.theme.fonts.fontSize}

但是,在全球在技术上高于theme.js的情况下,我如何以同样的方式传递给theme.js?这样我就可以创建一个全局样式

代码语言:javascript
复制
injectGlobal`
  html {
    font-size: (${props => props.theme.fonts.fontSize} / 16px) * 1em;
  }
`
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-28 06:47:19

解决这一问题的最简单方法是创建一个顶级组件,该组件将您想要的样式注入如下所示:

代码语言:javascript
复制
import { Children } from 'react';
import { withTheme, injectGlobal } from 'styled-components';

const GlobalComponent = ({ theme, children }) => {
  injectGlobal`
      font-size: ${theme.fonts.fontSize}
    }
  `;
  return Children.only(children);
};

export default withTheme(Global);

这将确保所有将此组件作为父组件的组件都具有所需的globalStyling。希望这能帮上忙

票数 4
EN

Stack Overflow用户

发布于 2021-03-11 13:36:28

现在,我们可以创建一个全局组件,并将其作为ThemeProvider的子组件传递。它将允许您访问当前theme的所有支持。

应用字体系列的示例:

你的Global.js / Global.ts

代码语言:javascript
复制
import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`

  html,
  body {
    padding: 0;
    margin: 0;
    font-family: ${(props) => props.theme.font.family}
  }

  a {
    color: inherit;
    text-decoration: none;
  }

  * {
    box-sizing: border-box;
  }
`;

export default GlobalStyle;

您的主要组件app.tsx / app.jsx

代码语言:javascript
复制
import theme...
import { ThemeProvider } ...
imort GlobalStyle from '../path-to-global-file';

const App ...
.
.
return(
 <>
  <ThemeProvider theme={theme}>
   <GlobalStyle />
   { /* Root component */ }
   <Component/>
  </ThemeProvider>
 </>
);

你现在可以很容易地使用道具了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50560238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档