141、React.js 父组件向子组件共享数据

本文深入探讨了React中上下文API的使用方法,包括如何在父组件中定义和传递数据,以及子孙组件如何接收和使用这些数据。通过具体示例,讲解了getChildContext、childContextTypes和contextTypes的作用及实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import React from 'react'
import ReactTypes from 'prop-types'

// 最外层的父组件
// export default class Com1 extends React.Component {

//     constructor(props) {
//         super(props)

//         this.state = {
//             color: 'red'
//         }

//     }

//     render() {

//         return <div>
//             <h3>这是父组件</h3>
//             <Com2 color={this.state.color}>Com2</Com2>
//         </div>
//     }

// }



// // 中间的子组件
// class Com2 extends React.Component {



//     render() {

//         return <div>
//             <h2>这是子组件</h2>
//             <Com3 color={this.props.color}></Com3>
//         </div>
//     }

// }


// // 中间的子组件
// class Com3 extends React.Component {



//     render() {

//         return <div>
//             <h1 style={{ color: this.props.color }}>这是孙子组件</h1>
//         </div>
//     }

// }






export default class Com1 extends React.Component {

    constructor(props) {
        super(props)

        this.state = {
            color: 'red'
        }

    }


    // 1、在父组件中,定义一个function ,这个function有个固定的名称,叫做getChildContext,内部必须返回一个对象
    // 这个对象,就是要共享给所有子孙组件的数据类型,
    getChildContext() {

        return {
            color: this.state.color
        }

    }

    //2、使用属性校验,规定一下传递给子组件的数据类型,需要定义一个静态的(static)
    // getChildContextTypes 固定名称,不要改
    static childContextTypes = {
        color: ReactTypes.string //规定了 传递给子组件的数据类型



    }



    render() {
        return <div>
            <h3>这是父组件</h3>
            <Com2>Com2</Com2>
        </div>
    }

}



// 中间的子组件
class Com2 extends React.Component {



    render() {

        return <div>
            <h2>这是子组件</h2>
            <Com3></Com3>
        </div>
    }

}


// 中间的子组件
class Com3 extends React.Component {

    //3、上来之后,先来个属性校验,去校验一下父组件传递过来的参数类型
    static contextTypes = {
        color: ReactTypes.string  //这里如果子组件,想要使用父组件,通过context共享的数据,那么在使用
        //之前,一定要先做一下数据类型校验
    }

    render() {

        return <div>
            <h1 style={{ color: this.context.color }}>这是孙子组件-----{this.context.color}</h1>
        </div>
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值