使用 styled-components 为组合组件设置主题的首选方法是什么?

What is the preferred way to theme a composed component using styled-components?

任何人都可以推荐编写需要主题的 styled-component 的最佳方法吗?

这是我的代码:https://gist.github.com/aaronmcadam/7bfd63a6bc4cfc36f9947a449c6f494a

我有一个 Avatar 组件,它组成了一个 Image 组件,它本身就是一个 styled-component

如果我使用Avatar.styled.js<ThemeProvider>,主题可以成功覆盖。

如果我使用Avatar.withTheme.js,主题只能在我使用withTheme时被覆盖。

执行这些操作的首选方法是什么?

来自官方文档:https://github.com/styled-components/styled-components/blob/master/docs/theming.md

We export a component that takes a theme prop. The theme you provide there is injected into your styled components via props.theme

If you ever need to get the current theme outside styled components (e.g. inside big components), you can use the withTheme Higher Order Component

import { withTheme } from 'styled-components'

class MyComponent extends React.Component {
  render() {
    const { theme } = this.props

    console.log('Current theme: ', theme);
    // ...
  }
}

export default withTheme(MyComponent)