react 孙组件调用爷爷的属性

本文介绍了在React中,如何通过使用Context API来实现孙组件调用祖父组件的属性。示例代码展示了创建ThemeContext,定义LifeCycle组件和SubCounter子组件,并在SubCounter中通过contextType访问上下文中的属性。同时,展示了组件生命周期方法componentWillReceiveProps、shouldComponentUpdate和componentWillUnmount的使用。

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

import React, { Component } from ‘react’
const ThemeContext = React.createContext();
export default class LifeCycle extends Component {

static defaultProps = {
    name : "计数器"
}
constructor(props){
    super(props);
    this.state = {number:0};//初始化默认状态对象
    console.log("1.初始化");
}
componentWillMount(){
    console.log("2.组件将要挂载");
}
componentDidMount(){
    console.log("4.组件挂载完成");
}
shouldComponentUpdate(){
    console.log("5.询问组件是否需要更新");
    return true;
}
componentWillUpdate(){
    console.log("6.组件将要更新");
}
componentDidUpdate(){
    console.log("7.组件更新完成");
}
add = () =>{
    this.setState({
        number:this.state.number+1
    });
}
render() {
    console.log("3.6-7.渲染阶段");
    **const props = {
        color:"red"
    }**
    return (
        **<ThemeContext.Provider value = {props}>**
        <div>
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值