我是靠谱客的博主 多情项链,这篇文章主要介绍react 父组件传值子组件,子组件传值孙组件,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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> <h1>这是 父组件 </h1> <Com2 color={this.state.color}></Com2> </div> } } // 中间的子组件 class Com2 extends React.Component { render() { return <div> <h3>这是 子组件 </h3> <Com3 color={this.props.color}></Com3> </div> } } // 内部的孙子组件 class Com3 extends React.Component { render() { return <div> <h5 style={{ color: this.props.color }}>这是 孙子组件 </h5> </div> } } */ // 最外层的父组件 export default class Com1 extends React.Component { constructor(props) { super(props) this.state = { color: 'red' } } // getChildContextTypes // 1. 在 父组件中,定义一个 function,这个function 有个固定的名称,叫做 getChildContext ,内部,必须 返回一个 对象,这个对象,就是要共享给 所有子孙自建的 数据 getChildContext() { return { color: this.state.color } } // 2. 使用 属性校验,规定一下传递给子组件的 数据类型, 需要定义 一个 静态的(static) childContextTypes(固定名称,不要改) static childContextTypes = { color: ReactTypes.string // 规定了 传递给子组件的 数据类型 } render() { return <div> <h1>这是 父组件 </h1> <Com2></Com2> </div> } } // 中间的子组件 class Com2 extends React.Component { render() { return <div> <h3>这是 子组件 </h3> <Com3></Com3> </div> } } // 内部的孙子组件 class Com3 extends React.Component { // 3. 上来之后,先来个属性校验,去校验一下父组件传递过来的 参数类型 static contextTypes = { color: ReactTypes.string // 这里,如果子组件,想要使用 父组件通过 context 共享的数据,那么在使用之前,一定要先 做一下数据类型校验 } render() { return <div> <h5 style={{ color: this.context.color }}>这是 孙子组件 --- {this.context.color} </h5> </div> } }

 

最后

以上就是多情项链最近收集整理的关于react 父组件传值子组件,子组件传值孙组件的全部内容,更多相关react内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部