本文介绍了如何在样式组件之外获取主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

const StyledView = styled.View`颜色:${({主题}) =>主题颜色};`;

但是如何从普通组件获取或将其应用于不同属性?示例:

index.js

<主要/></ThemeProvider>

main.js

<卡片 aCustomColorProperty={从主题中获取颜色}/></查看>

注意需要主题的属性如何不被称为style

解决方案
import { withTheme } from 'styled-components'class MyComponent 扩展了 React.Component {使成为() {const { 主题 } = this.propsconsole.log('当前主题:', 主题);//...}}导出默认 withTheme(MyComponent)

以下为原帖

我现在想出的解决方案:

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

从'react'导入React;从'styled-components/lib/models/ThemeProvider'导入{频道};导出默认组件 =>类扩展 React.Component {静态上下文类型 = {[频道]: React.PropTypes.func,};状态 = {主题:未定义,};componentWillMount() {const subscribe = this.context[CHANNEL];this.unsubscribe = 订阅(主题 => {this.setState({ 主题 })});}componentWillUnmount() {if (typeof this.unsubscribe === 'function') this.unsubscribe();}使成为() {const { 主题 } = this.state;return <Component theme={theme} {...this.props}/>}}

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

从 './Themable.js' 导入 Themableconst 组件 = ({ 主题 }) =><卡片颜色={theme.color}/>导出默认主题(组件);

I know how to get the theme from components that are created using the styled way:

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

But how to get from normal components or apply it for different properties? Example:

index.js

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

main.js

<View>
    <Card aCustomColorProperty={GET COLOR FROM THEME HERE} />
</View>
解决方案
import { withTheme } from 'styled-components'

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

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

export default withTheme(MyComponent)


Solution I came up by now:

Create a Higher Order Component that will be responsable to get the current theme and pass as a prop to a component:

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} />
  }
}

Then, call it on the component you need to access the theme:

import Themable from './Themable.js'

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

export default Themable(Component);

这篇关于如何在样式组件之外获取主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:44