React Context

2019-06-20  本文已影响0人  中石化局长

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>
    );
  }
}
上一篇 下一篇

猜你喜欢

热点阅读