首页 > 解决方案 > 在 `createGlobalStyle` 中使用样式化组件的规则

问题描述

样式化组件的新手,想知道是否有人可能对如何在调用中使用样式化组件的规则有一些建议createGlobalStyle

下面的示例正在运行,但我觉得这不是一个很好的解决方案,因为componentStyle.rules官方 api 文档中没有。

// A styled component
import Modal from '../Modal'
import styled, { createGlobalStyle } from 'styled-components'

const StyledComponent = styled(Modal)`
  background-color: pink;  
`

createGlobalStyle`
  // this div is mounted outside of the React root
  .modal-from-external-library {
    ${StyledComponent.componentStyle.rules}
  }
`

标签: javascriptreactjsstyled-components

解决方案


不确定我尝试做的事情是否可行,但我最终通过使用css样式组件的功能从 Modal 导出 css 来解决问题。

// Modal.js

const styles = css`
  // styles here
`

export default styled.div`
  ${styles}
`

// ... later 
const GlobalStyles = createGlobalStyle`${styles}`

render() { return (<GlobalStyles {...props} />) }


推荐阅读