React里面的Context应用示例
// 1. 创建上下文 createContext() import React, { Component } from 'react'; const Context = React.createContext(); const store = { name: '小毛', sayHi(){ console.log(this.name) } } export default ContextSample extends Component{ render(){ return( <div> <Context.Provider value={store}> <div> <Context.Consumer> { /* 必须要一个函数 */} { value => <div onClick={() => value.sayHi()}>{value.name}</div> } </Context.Consumer> </div> </Context.Provider> </div> ) } }
<Context.Provider> 和 <Context.Consumer> 那样定义着写在那里,看着有点别扭。可以定义装饰器来渲染
const withProvider = Comp => props => ( <Context.Provider value={store}> <Comp {...props} /> </Context.Provider> ) const withConsumer = Comp => props => ( <Context.Consumer> { value => <Comp {...props} value={value} /> } </Context.Consumer> )
然后调用装饰器,修改代码
@withConsumer class Inner extends Component{ render(){ return <div onClick={() => this.props.value.sayHi()}> { this.props.value.name } </div> } } @withProvider class ContextSample extends Component { render() { return ( <div> <Inner /> </div> ) } } export default ContextSample;
React的context是vuejs的provide&inject的来源,由高层组件向底层组件传值