SASS Bootstrap allows us to configure theme or branding variables that affect all components (e.g. Primary Color or Link Color). When we isolate our styles inside React components we lose the ability to theme them. To get round this we can put our theme variables on the context of our app and then read them from individual components in order to make styling decisions. Recompose allows us to create the helper functions we need to do this yielding concise, functional declarative UI components. These components will respond in real time to changes in the theme.

We have a default theme file:

export default {
color: {
keyColor: '#3f8bae',
textLight: '#fff',
},
number: {
buttonRadius: 5
},
string: {
mainFontFamily: 'sans-serif'
}
}

We want Component get defualt theme according to the file.

We will build an interface to update theme according to user input.

We can import theme file into the App.js compoent and pass down to the custom component. The problem is that, if we have hunders components, it is not ideal to passdown the props hundres times.

That's why we need context.

We can use 'recompose' to do that:

import React, { Component } from 'react';
import {compose, withState} from 'recompose'; import myDefaultTheme from './themes/default';
import Button from './components/Button'; class App extends Component {
static childContextTypes = {
theme: React.PropTypes.object
}; getChildContext() {
return {theme: this.props.theme}
} render() {
const {theme, updateTheme} = this.props;
return (
<div className="App">
<main className="container">
...
</main>
</div>
);
}
} const enhance = compose(
withState('theme', 'updateTheme', myDefaultTheme)
);
export default enhance(App);

So for this part of code:

const enhance = compose(
withState('theme', 'updateTheme', myDefaultTheme)
);
export default enhance(App);

We wrap our App component with 'enhance' to update component props.

widthState function: Passes two additional props to the base component: a state value, and a function to update that state value. so 'updateTheme' will take nextProps to udpate current props.

    static childContextTypes = {
theme: React.PropTypes.object
}; getChildContext() {
return {theme: this.props.theme}
}

Those code helps us to pass 'theme' down to children components.

Also need to create a file called "hocs.js" which means high order component. This file contains reusable methods to update the custom component.

To get context from 'App.js', we need 'getContext' method form 'recompose':

export const getTheme = getContext({
theme: PropTypes.shape({
color: PropTypes.object,
number: PropTypes.object,
string: PropTypes.object
})
});

We also need a 'themeStyle' method to update style:

export const themeStyle = mapThemeToStyle => mapProps(
props => {
const { theme, style } = props; return {
...props,
style: [
mapThemeToStyle(theme, props),
style
]
};
}
);

It takes a updater function called 'mapThemeToStyle' which can map theme to style according to different components needs.

Now in the custom component, let compose those:

import React from 'react';
import {
mapProps,
compose,
defaultProps,
setDisplayName,
componentFromProp
} from 'recompose';
import Radium from 'radium'; import {
getTheme,
themeStyle,
addStyle
} from './hocs'; const mapThemeToStyle = ({
color,
number,
string
}) => {
return {
...(color.keyColor &&
{backgroundColor: color.keyColor} || {}
),
color: color.textLight,
borderRadius: number.buttonRadius,
fontFamily: string.mainFontFamily
};
}; const style = {
backgroundColor: 'red',
borderWidth: ,
borderStyle: 'solid',
boxSizing: 'border-box',
fontFamily: 'sans-serif',
fontSize: ,
borderRadius: ,
fontWeight: ,
padding: ,
verticalAlign: 'middle',
whiteSpace: 'nowrap',
color: 'white',
alignItems: 'center',
justifyContent: 'center',
textDecoration: 'none',
display: 'flex',
flex: ,
cursor: 'pointer',
':hover': {
backgroundColor: 'purple'
}
}; const enhance = compose(
getTheme, // using the container's defined theme
themeStyle(mapThemeToStyle), // apply the default theme to the component
addStyle(style),
setDisplayName('Button'),
defaultProps({
element: 'button'
}),
Radium
);
export default enhance(componentFromProp('element'));

[React] Recompose: Theme React Components Live with Context的更多相关文章

  1. [React] Render Text Only Components in React 16

    In this session we create a comment component to explore how to create components that only render t ...

  2. react初探索--react + react-router + ant-design 后台管理系统配置

    首先确认安装了node环境,Node >= 6. 如果对react 及 ant-design 一无所知,建议去阅读下api文档,react 可以在 codePen 在线练习. react Api ...

  3. react新特性 react hooks

    本文介绍的是react新特性react hooks,本文面向的是有一定react开发经验的小伙伴,如果你对react还不是很熟悉的话我建议你先学习react并多多联系. 首先我们都知道react有3种 ...

  4. [react] 细数 React 的原罪

    Props & onChange 的原罪 .「props & onChange 接口规范」它不是一个典型的「程序接口规范」. 当你拿到一个可视组件的 ref,却没有类似 setProp ...

  5. React笔记:React基础(2)

    1. JSX JSX是一种拥有描述UI的JavaScript扩展语法,React使用这种语法描述组件的UI. 1.1 基本语法 JSX可以嵌套多个HTML标签,可以使用大部分符号HTML规范的属性. ...

  6. 【React Native】React Native项目设计与知识点分享

    闲暇之余,写了一个React Native的demo,可以作为大家的入门学习参考. GitHub:https://github.com/xujianfu/ElmApp.git GitHub:https ...

  7. react聊天室|react+redux仿微信聊天IM实例|react仿微信界面

    一.项目概况 基于react+react-dom+react-router-dom+redux+react-redux+webpack2.0+react-photoswipe+swiper等技术混合开 ...

  8. React源码 React.Component

    React中最重要的就是组件,写的更多的组件都是继承至 React.Component .大部分同学可能都会认为 Component 这个base class 给我们提供了各种各样的功能.他帮助我们去 ...

  9. WHAT IS THE DIFFERENCE BETWEEN REACT.JS AND REACT NATIVE?

    Amit Ashwini - 09 SEPTEMBER 2017 React.js was developed by Facebook to address its need for a dynami ...

随机推荐

  1. 简单的横向ListView实现(version 4.0)

    这个版本号的博客写起来颇费口舌.有些代码自己语言组织能力有限,感觉描写叙述起来非常费劲,前前后后改了五六遍稿子还是不尽人意 ,只是我还是坚持写出来自己当初的思路,假设看得不明确的地方我在文章最后仍然会 ...

  2. css 0.5px

    1. 利用css3新属性scale(好用推荐) 其实现的关键就是利用before或after伪元素,宽高同时设为200%,然后再缩放0.5,自然就是0.5px了 代码如下: div { positon ...

  3. Mongodb总结4-Spring环境使用Mongodb

    前几次的例子,要么是Shell,要么是普通Java应用程序的例子.实际情况,是要在Spring的项目里用,因此需要做一些改造. 1.配置文件C:\hanhai\config\mongodb.prope ...

  4. debian 9 安装后需做的几件事

    debian 9 安装后需做的几件事 安装环境:X86 >> Debian 9 Linux/GNU apt源更新 注意连上有线网络 刚安装好的debian系统中,/etc/apt/sour ...

  5. [TypeScript@2.5] Omit catch error block if not needed

    From TypeScript@2.5, you can omit catch error block. Before: try { throw new Error('whatever'); } ca ...

  6. (转)linux screen 命令详解

    转自:http://www.cnblogs.com/mchina/archive/2013/01/30/2880680.html 一.背景 系统管理员经常需要SSH 或者telent 远程登录到Lin ...

  7. Day1:循环语句(While,For)

    一.while循环 while 条件: 条件为真执行的语句 esle: 条件为假执行的语句 #!/usr/bin/env python # -*- coding:utf-8 -*- # Author: ...

  8. 【例题5-3 UVA - 10815】Andy's First Dictionary

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 用stringstream来处理中间的标点. ->直接把他变成一个空格. 然后重新输入进去. set默认的字典序就是升序的了. ...

  9. [Angular2 Form] Angular 2 Template Driven Form Custom Validator

    In this tutorial we are going to learn how we can also implement custom form field validation in Ang ...

  10. iOS中OC给Category加入属性

    引: 非常多人知道能够用Category给已有的类加入一些新方法,可是不同于swift中的extension,Objective-C中的Category(类别)是不支持直接加入属性的.那假设就是须要加 ...