在Global Styled-Components中使用ThemeProvider道具

时间:2018-05-28 06:20:12

标签: javascript reactjs styled-components

使用 styled-components 时如何访问ThemeProvider中的props global.js

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

const theme = {
    fonts: {
        fontSize : '16px',
    }
}

export default theme

这在/layouts/index.js中提供为

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}

但是,如果全球技术上的水平高于global.js,我怎么能以同样的方式传递给theme.js?这样我就可以创建一个全局样式

injectGlobal`
  html {
    font-size: (${props => props.theme.fonts.fontSize} / 16px) * 1em;
  }
`

2 个答案:

答案 0 :(得分:2)

解决此问题的最简单方法是创建一个顶级组件,以此方式注入您想要的样式:

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);

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

答案 1 :(得分:1)

晚了,但现在我们实际上可以创建一个全局组件并将其作为 ThemeProvider 的子项传递。它将允许您访问当前 theme 的所有道具。

应用字体系列的示例:

您的Global.js / Global.ts

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

import theme...
import { ThemeProvider } ...
imort GlobalStyle from '../path-to-global-file';

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

您现在可以轻松使用道具了。

相关问题