SOURCE

/*
 * @Author: funlee
 * @Email: i@funlee.cn
 * @Date: 2019-06-06 14:52:06
 * @Description: 16.3 新版实现
 * Context 主要应用场景在于很多不同层级的组件需要访问同样一些的数据。请谨慎使用,因为这会使得组件的复用性变差。
 */
import React, { Component } from 'react';

const ThemeContext = React.createContext({ theme: 'red' });

class Button extends Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {({ color }) => {
          return (
            <button style={{ background: color }}>
              {this.props.children}
            </button>
          )
        }}
      </ThemeContext.Consumer>
    )
  }
}

class Message extends React.PureComponent { // pur
  render() {
    const { id, value } = this.props.data
    return (
      <li>
        {`The ${id} is ${value}`} ---- <Button>Delete</Button>
      </li>
    )
  }
}

class MessageList extends Component {
  state = {
    theme: {
      color: 'red'
    }
  };
  changeColor() {
    const colors = ['red', 'pink', 'blue'];
    const index = (colors.indexOf(this.state.theme.color) + 1) % 3;
    this.setState({
      theme: {
        color: colors[index]
      }
    })
  }
  render() {
    const children = this.props.messages.map(message =>
      <Message data={message} key={message.id} />
    )
    return (
      <ThemeContext.Provider value={this.state.theme}>
        <div>
          <ul>
            {children}
          </ul>
          <button onClick={() => this.changeColor()}>Change Color</button>
        </div>
      </ThemeContext.Provider>
    )
  }
}

export default class TestContext extends Component {
  render() {
    const messages = [
      { id: 'name', value: 'funlee' },
      { id: 'age', value: 18 },
      { id: 'skill', value: 'React' }
    ]
    return <MessageList messages={messages} />
  }
};
console 命令行工具 X clear

                    
>
console