React Context的使用方法

相关文章:react Provider Consumer 使用方法

背景:在某些场景下,你想在整个组件树中传递数据,但却不想手动地在每一层传递属性,你可以直接在React中使用强大的contextAPI 解决上述问题

在一个典型的React 中,数据通过Props属性自下而上(由父及子)进行传递的,但这种做法对于某些类型的属性而言机器繁琐,(地区偏好,UI主题)这些属性是应用程序中许多组件都需要的。Context提供了一种在组件之间共享此值的方式,而不必显式的通过组件树逐层传递props

contextType只能用在类组件里
Consumer一般用在函数组件中

import React from './react';
import ReactDOM from './react-dom';
let ThemeContext = React.createContext();
/* let ThemeContext = React.createContext();
let { Provider, Consumer } = ThemeContext; */
//ThemeContext={Provider,Consumer} Consumer一般用在函数组件中
function Header(){
  return (
    <ThemeContext.Consumer>
      {
        value=>(
          <div style={{ margin: '10px', border: `5px solid ${value.color}`, padding: '5px' }}>
            头部
          </div>
        )
      }
    </ThemeContext.Consumer>
  )
}
class Main extends React.Component {
  static contextType = ThemeContext
  render() {
    return (
      <div style={{ margin: '10px', border: `5px solid ${this.context.color}`, padding: '5px' }}>
        主体
        <Content />
      </div>
    )
  }
}
class Content extends React.Component {
  static contextType = ThemeContext
  render() {
    return (
      <div style={{ margin: '10px', border: `5px solid ${this.context.color}`, padding: '5px'}}>
        内容
        <button onClick={()=>this.context.changeColor('red')}>变红</button>
        <button onClick={()=>this.context.changeColor('green')}>变绿</button>
      </div>
    )
  }
}
class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: 'red' };
  }
  changeColor = (color) => {
    this.setState({ color });
  }
  render() {
    let contextValue = { color: this.state.color, changeColor: this.changeColor };
    return (
      <ThemeContext.Provider value={contextValue}>
        <div style={{ margin: '10px', border: `5px solid ${this.state.color}`, padding: '5px', width: '200px' }}>
          主页
           <Header />
          <Main />
        </div>
      </ThemeContext.Provider>
    )
  }
}
ReactDOM.render(<Page />, document.getElementById('root'));

react.js中相关代码

function createContext(){
    function Provider({value,children}){
        Provider._value = value;
        return children;
    }
    function Consumer({children}){
       return children(Provider._value);
    }
    return {Provider,Consumer};
}
  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小超人rui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值