繁体   English   中英

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

[英]Using ThemeProvider props in Global Styled-Components

使用styled-components时如何访问global.jsThemeProvider props

例如在 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;
  }
`

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

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。 希望这有帮助

晚了但现在我们实际上可以创建一个全局组件并将其作为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>
 </>
);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM