【问题标题】:Using ThemeProvider props in Global Styled-Components在全局样式组件中使用 ThemeProvider 道具
【发布时间】:2021-05-20 13:32:08
【问题描述】:

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

例如在 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 =&gt; props.theme.fonts.fontSize}

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

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

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

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

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

    这将确保以该组件为父级的所有组件都将具有所需的全局样式。希望这有帮助

    【讨论】:

    • 谢谢。这是有道理的,但它会传递给诸如html 之类的值,还是传递给低于html 的顶级组件?
    • 通常injectGlobal 会解决这个问题,我会说用background-color: 'pink' 这样的明显例子来试试。这样可以确保您有一个明显的视觉队列。
    • 现在试一试。快速提问...withTheme 是什么意思?那不需要定义吗?
    • withTheme 是由styled-components 导出的,它是一个将主题注入到道具中的HighOrder 组件。对不起,我忘了提到那个导入。
    • 为您添加了导入,确保您使用正确的东西 :) 祝您好运。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2021-05-10
      • 2020-10-23
      • 2018-12-11
      • 2022-01-10
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多