Context-上下文

import React, { Component } from 'react';
import { Button } from 'antd'
const Them = React.createContext()

class Btn extends Component {
  // 1. 使用 `contextType`
  // static contextType = Them
  render() {
    // return <Button type={this.context.type}>{this.context.name}</Button>
    
    // 2. 使用 `Consumer` 类定义
    return (
      <Them.Consumer>
        {
          value => {
            return <Button type={value.type}>{value.name}</Button>
          }
        }
      </Them.Consumer>
    )
  }
}

class Toolbar extends Component {
  render() {
    return <Btn></Btn>
  }
}

class ContextSimple extends Component {
  constructor(props){
    super(props)
    this.state = {
      store: {
        type: 'default',
        name: '按钮2'
      }
    }
  }
  render() {
    return (
      <div>
        <Them.Provider value={this.state.store}>
          <Toolbar></Toolbar>
        </Them.Provider>
      </div>
    );
  }
}

export default ContextSimple;

liuoomei
175 声望18 粉丝

走出舒适区,外面的风景格外迷人!