react中的Context

199 阅读1分钟

Context 提供了一种在组件之间共享此类值的方式,而不必显式地通过组件树的逐层传递props。谨慎使用,会使组件复用性变差。 几种写法:

  • 1、以Context.Consumer、Context.Provider方式
  • 2、以Class.ContextType形式使用
  • 3、Hook中使用useContext

当 Provider 的 value值发生变化时,它内部的所有消费组件都会重新渲染。Provider 及其内部 consumer 组件都不受制于 shouldComponentUpdate 函数,因此当 consumer 组件在其祖先组件退出更新的情况下也能更新

const themes = {
    light: {
        foreground: '#ffffff',
        background: '#222222',
    },
    dark: {
        foreground: '#000000',
        background: '#eeeeee',
    },
};
const ThemeContext = React.createContext(themes.light);

//以Context.Consumer、Context.Provider方式
function Child1(){
    return (
        <ThemeContext.Consumer>
            {
                value => <div>
                    孙节点1: {value.background}
                </div>
            }
        </ThemeContext.Consumer>
    )
}

//以Class.ContextType静态属性形式使用
class Child2 extends React.Component{
  static contextType = ThemeContext;
  render(){
    const value = this.context;
    return <div>
        孙节点2:{value.background}
    </div>
  }
}

//Hook中使用useContext
function Child3(){
  const value = React.useContext(ThemeContext);
  return <div>
    孙节点3:{value.background}
  </div>
}


const Son = () => {
    return (
        <div>
            <span>子节点</span>
            <Child1/>
            <Child2/>
            <Child3/>
        </div>
    );
}

const Parent = () => {
    let [theme, setTheme] = React.useState('light');
    return (
        <ThemeContext.Provider value={themes[theme]}>
            <button onClick={(e) => { setTheme('dark') }}>dark</button>
            <button onClick={(e) => { setTheme('light') }}>light</button>
            <Son></Son>
        </ThemeContext.Provider>
    );
};


ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);

官方连接:

zh-hans.reactjs.org/docs/contex…

zh-hans.reactjs.org/docs/hooks-…