如何使用React的Context呢
详细查看官方文档
1 什么是 Context
Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。
2 使用方法
1.创建Context容器对象:
const XxxContext = React.createContext()  2.渲染子组件时,外面包裹xxxContext.Provider, 通过value属性给后代组件传递数据:
<xxxContext.Provider value={数据}>
    子组件
</xxxContext.Provider>3.后代组件读取数据:
//第一种方式:仅适用于类组件 
  static contextType = xxxContext  // 声明接收context
  this.context // 读取context中的value数据
//第二种方式: 函数组件与类组件都可以
  <xxxContext.Consumer>
    {
      value => ( // value就是context中的value数据
        要显示的内容
      )
    }
  </xxxContext.Consumer>小案例如下
import React, { Component } from 'react';
import '../../css/context.css'
//创建一个用于保存用户名的上下文
const UsernameContext = React.createContext()
const {Consumer} = UsernameContext
class Context extends Component {
    state = {
        username: 'contextUsername',
        age: 18
    }
    render() {
        return (
            <div className="parent">
                <h1>我是Context组件</h1>
                <h2>我的用户名是:{this.state.username}</h2>
                <UsernameContext.Provider value={{username:this.state.username,age:this.state.age}}>
                    <ContextA></ContextA>
                </UsernameContext.Provider>
            </div>
        );
    }
}
class ContextA extends Component {
    render() {
        return (
            <div className="child">
                <h1>我是ContextA组件</h1>
                <h2>我从Context组件获取到的用户名是:</h2>
                <ContextB></ContextB>
            </div>
        );
    }
}
// class ContextB extends Component {
//     static contextType = UsernameContext  //声明接收context
//     render() {
//         console.log(this.context)
//         return (
//             <div className="children">
//                 <h1>我是ContextB组件</h1>
//                 <h2>我从Context组件获取到的用户名是:{this.context.username},年龄是:{this.context.age}</h2>
//             </div>
//         );
//     }
// }
function ContextB() {
    return (
        <div className="children">
                <h1>我是ContextB组件</h1>
                <h2>我从Context组件获取到的用户名是:
                    <Consumer>
                        {
                            (value) =>{
                                console.log(value)
                                return `${value.username},年龄是:${value.age}`
                            }
                        }
                </Consumer> 
                </h2>
        </div>
    );
}
export default Context;效果如下图:

- 本文作者: étoile
 
- 版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!