爷爷组件
import React, { Component } from "react";
import "./App.css";
import TestHanderClick from "./components/TestHanderClick";
import proptypeskey from "prop-types";
export class App extends Component {
// 也是人家提供的,不可以改变 传递给孙子组件的类型(必须写)
// 爷爷组件传递给孙子组件,依赖于 prop-types;(验证参数的格式)
static childContextTypes = {
title: proptypeskey.string,
};
// getChildContext是人家提供的,设置穿度的内容(必须写)
getChildContext() {
return {
title: "营业员==>给孙子的",
};
}
render() {
return (
<div className="App">
{/* 父组件传递给子组件的值 */}
<TestHanderClick></TestHanderClick>
</div>
);
}
}
export default App;
父亲组件(父亲组件啥子都不用干)
import React, { Component } from "react";
import "./base.css";
import SuoZi from "./SuoZi";
// 父组件
export class TestHanderClick extends Component {
// static defaultProps是默认的写法,人家规定这样写的,你的默认值
static defaultProps = {
bg: "pink",
wi: "400px",
he: "200px",
};
render() {
return (
// 使用值
<div
style={{
background: this.props.bg,
this.props.wi,
height: this.props.he,
}}
>
<SuoZi></SuoZi>
</div>
);
}
}
export default TestHanderClick;
孙子组件
import React, { Component } from "react";
// 引入验证格式类型的插件
import proptypeskey from "prop-types";
export class SuoZi extends Component {
// 也是人家提供的,不可以改变(必须写)
static contextTypes = {
title: proptypeskey.string,
};
render() {
return (
<div>
{/* 获取值 */}
<p>爷爷=={this.context.title} </p>
</div>
);
}
}
export default SuoZi;