小编典典

如何在样式组件之外获得主题?

reactjs

我知道如何theme从使用以下styled方式创建的组件中获取:

const StyledView = styled.View`
    color: ${({ theme }) => theme.color};
`;

但是,如何从 常规组件中 获得或将其应用于 不同的属性 呢?例:

index.js

<ThemeProvider theme={{ color: 'red' }}>
    <Main />
</ThemeProvider>

main.js

<View>
    <Card aCustomColorProperty={GET COLOR FROM THEME HERE} />
</View>

注意,没有调用需要主题的属性 style


阅读 274

收藏
2020-07-22

共1个答案

小编典典

编辑:从v1.2开始,我的请求请求已合并,您可以通过以下方式使用 withTheme高阶组件:

import { withTheme } from 'styled-components'

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

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

export default withTheme(MyComponent)

下面的原始帖子

解决方案我现在想出了:

创建一个高阶组件,该组件将负责获取当前主题并将其作为道具传递给组件:

import React from 'react';
import { CHANNEL } from 'styled-components/lib/models/ThemeProvider';

export default Component => class extends React.Component {
  static contextTypes = {
    [CHANNEL]: React.PropTypes.func,
  };

  state = {
    theme: undefined,
  };

  componentWillMount() {
    const subscribe = this.context[CHANNEL];
    this.unsubscribe = subscribe(theme => {
      this.setState({ theme })
    });
  }

  componentWillUnmount() {
    if (typeof this.unsubscribe === 'function') this.unsubscribe();
  }

  render() {
    const { theme } = this.state;

    return <Component theme={theme} {...this.props} />
  }
}

然后,在您需要访问的组件上调用它theme

import Themable from './Themable.js'

const Component = ({ theme }) => <Card color={theme.color} />

export default Themable(Component);
2020-07-22