React Context

redux原理跟其类似,redux的provider就是用context实现的

使用:

//先定义一个context
const ThemeContext = React.createContext({
  background: 'red',
  color: 'white'
});
...
//在爷爷组件里包裹一个父组件设置provider,如果不设置,就会使用默认的"red"
<ThemeContext.Provider value={{background: 'green', color: 'white'}}>
      <Toolbar />
</ThemeContext.Provider>
...
//父组件,有多少都行
function Toolbar(props) {
    return (
        <div>
            <ThemedButton />
        </div>
    );
}
...

老API的写法

class ThemedButton extends React.Component {
//要使用的孙组件里定义contextType
  static contextType = ThemeContext;
//然后this.context就可以直接使用了
  render() {
      return <Button style={{ 'background':this.context }} />;
  }
}

或者在孙组件中(新API写法)

class ThemedButton extends React.Component {
  render () {
    return (
      <ThemeContext.Consumer>
        {context => (
          <h1 style={{background: context.background, color: context.color}}>
            {this.props.children}
          </h1>
        )}
      </ThemeContext.Consumer>
    );
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容