1. 程式人生 > 實用技巧 >React跨元件通訊

React跨元件通訊

import React, { Component ,createContext} from 'react'

console.log(createContext())
const {
    Provider, //提供者
    Consumer:CounterConsumer //接收者
} = createContext()

class CounterProvider extends Component{
    constructor () {
        super()
        this.state = {
            count:100
        }
    }

    incrementCount 
= () => { this.setState({ count:this.state.count + 1 }) } decrementCount = () => { this.setState({ count:this.state.count - 1 }) } render() { return ( <Provider value={{ count:
this.state.count, incrementCount:this.incrementCount, decrementCount:this.decrementCount, }}> {this.props.children} </Provider> ) } } class Counter extends Component{ render(){ return(
<CounterConsumer> { ({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