react context 的使用

2019-12-16  本文已影响0人  阿畅_
import React, { Component, createContext } from 'react'
// 使用 Context 跨数据树,传递数据


const TestContext = createContext()
const OnlineContext = createContext()
class Grandson extends Component {
  render() {
    return (
      <TestContext.Consumer>
        {
          count => (
            <OnlineContext.Consumer>
              {
                online => <h1>count: { count }, online: { String(online) }</h1>
              }
            </OnlineContext.Consumer>
          )
        }
      </TestContext.Consumer>
    )
  }
}


class Child extends Component {
  render() {
    return <Grandson></Grandson>
  }
}

class Test extends Component {

  state = {
    online: false,
    count: 60
  }

  render() {
    const { count, online } = this.state
    return (
      <TestContext.Provider value={count} >
        <OnlineContext.Provider value={online}>
          <button type="button" onClick={() => this.setState({ online: !online })}>true</button>
          <button type="button" onClick={() => this.setState({ count: count - 1 })}>press</button>
          <Child/>
        </OnlineContext.Provider>
      </TestContext.Provider>
    )
  }
}

export default Test

contextType 的使用

class Grandson extends Component {
  static contextType = TestContext

  render() {
    const count = this.context
    return (
      <h1>count: { count }</h1>
    )
  }
}
上一篇下一篇

猜你喜欢

热点阅读