React跨组件通讯
import React, { Component ,createContext} from 'react' console.log(createContext()) const { Provider, //提供者 Consumer:CounterConsumer //解构出来重新赋值给一个CounterConsumer的组件 } = createContext() //封装一个基本的Provider,直接使用Provider,不方便管理状态 class CounterProvider extends Component{ constructor () { super() //这里的状态就是共享的,任何CounterProvider后代组件都可以通过CounterConsumer获取 this.state = { count:100 } } incrementCount = () => { this.setState({ count:this.state.count + 1 }) } decrementCount = () => { this.setState({ count:this.state.count - 1 }) } render() { return ( //使用Provider组件 ,它必须要有一个value值,可传递任何数据(一般传递对象) <Provider value={{ count:this.state.count, incrementCount:this.incrementCount, decrementCount:this.decrementCount, }}> {this.props.children} </Provider> ) } } class Counter extends Component{ render(){ return( <CounterConsumer> { //CounterConsumer的children必须是一个方法,这个方法有一个参数就是Provider组件的value ({count})=>{ return <span>{count}</span> } } </CounterConsumer> ) } } class CountBtn extends Component{ render(){ return( <CounterConsumer> { ({incrementCount,decrementCount})=>{ const handle = this.props.type == 'decrement' ? decrementCount : incrementCount return <button onClick={handle}>{this.props.children}</button> } } </CounterConsumer> ) } } //被提供者(CounterProvider)包囊的组件(CountBtn,Counter)都可以用(CounterConsumer)获得提供者的值 class Content extends Component { render() { return ( <CounterProvider> <div> <CountBtn type="decrement" >-</CountBtn> <Counter /> <CountBtn type="increment" >+</CountBtn> </div> </CounterProvider> ) } } export default Content