React组件间的Context传值

在一个典型的 React 应用中,数据是通过 props 属性自上而下(由父及子)进行传递的,代码如下

ThemeBtn 中想要获取到ContextSimple 中的 text 属性,需要将 text 属性从 ContextSimple 传递到
ToolBar,再传递到 ThemeBtn,可以想象假如有10层,那将极其繁琐!

Context提供了一种在组件之间共享值的方式,而不必显式地通过组件树的逐层传递 props。

import React, { Component } from 'react';

function ThemeBtn(props) {
  return (
    <div>{props.theme.text}</div>
  )
}

function ToolBar(props) {
  return <ThemeBtn {...props}></ThemeBtn>
}

class ContextSimple extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text:'按钮'
    };
  }
  render() {
    return (
      <ToolBar theme={this.state}></ToolBar>
    );
  }
}

export default ContextSimple;

如何使用 Context

创建一个Context对象

const ThemeContext = React.createContext();

Provider(订阅者):Provider 接收一个 value 属性,传递给消费者组件。
注意:这个value名字是固定的,不能改变,否则后面的消费者组件中获取不到属性值

<ThemeContext.Provider value={this.state}>

Consumer(消费者):这里,React 组件也可以订阅到 context 变更

<ThemeContext.Consumer>
   {
     value => <div>{value.name}</div>
   }
</ThemeContext.Consumer>

Context 完整使用代码:

import React, { Component } from 'react';

// 创建一个Context对象
const ThemeContext = React.createContext();
function ThemeBtn(props) {
  return (
    <ThemeContext.Consumer>
      {
        value => <div>{value.name}</div>
      }
    </ThemeContext.Consumer>
  )
}

function ToolBar(props) {
  return <ThemeBtn></ThemeBtn>
}

class ContextSimple extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '按钮'
    };
  }
  render() {
    return (
      <ThemeContext.Provider value={this.state}>
        <ToolBar></ToolBar>
      </ThemeContext.Provider>
    );
  }
}

export default ContextSimple;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值