React组件实现越级传递属性

import React, { Component } from 'react';
import PropTypes from 'prop-types';	//引入属性校验

// 父组件
// getChildContextTypes
// 1. 在 父组件中,定义一个 getChildContext 的函数,返回一个对象,这个对象就是要共享给 所有子孙自建的数据
// 2. 使用 属性校验,规定一下传递给子组件的 数据类型, 需要定义一个静态的(static) childContextTypes
export default class GetChildContext extends Component {
	constructor(props) {
		super(props);
		this.state = {
			color: 'red'
		};
	}

	static propTypes = {
		msg: PropTypes.string
	};

	getChildContext() {
		return {
			color: this.state.color
		};
	}

	static childContextTypes = {
		color: PropTypes.string
	};

	render() {
		return (
			<div>
				父组件
				<Con1 msg="中间件" />
			</div>
		);
	}
}

// 中间的子组件
function Con1(props) {
	return (
		<div>
			子组件 -- {props.msg}
			<Con2 />
		</div>
	);
}

// 内部的孙子组件
// 3. 先进行属性校验,去校验一下父组件传递过来的 参数类型
class Con2 extends Component {
  static contextTypes = {
    color: PropTypes.string
    // 如果子组件,想要使用 父组件通过 context 共享的数据,那么在使用之前,一定要先 做一下数据类型校验
  }

  render() {
    return (
      <div style={{color: this.context.color}}>孙子组件</div>
      // 引用方式 this.context.属性名
    )
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值