React组件间传值方式

react推崇的是单向数据流,自上而下进行数据的传递,但是由下而上或者不在一条数据流上的组件之间的通信就会变的复杂。
组件之间传递信息方式,总体可分为以下5种:

父组件向子组件传递信息

父组件向更深层的子组件(孙子组件)进行传递信息

子组件向父组件传递信息

没有任何嵌套关系的组件之间传值(兄弟组件之间传值)

利用react-redux进行组件之间的状态信息共享

1. 父组件向子组件传递信息

主要是通过 prop进行传值:

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
// 子组件
class Button extends Component{
constructor( props ){
super( props );
};
render(){
return(
<button style={{background: this.props.color }}>{this.props.children}</button>
)
}
}
// 父组件
class Message extends Component{
constructor( props ){
super( props );
this.state ={
color : "red"
}
};

render(){
return(
<div>
<Button color={this.state.color} />
//在父组件中将color属性通过prop传递给了子组件
</div>
)
}
}

2. 父组件向更深层的子组件进行传递信息

主要是利用context:
组件层级嵌套到比较深,可以使用上下文getChildContext来传递信息,这样就不需要将数据一层层往下传,
任何一层的子级都可以通过this.context直接访问。

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
// React 15.5版本以后, 使用PropTypes需要引入外部库
import PropTypes from 'prop-types';
// 子组件
class Button extends Component{
contextTypes = {
color: React.PropTypes.string // 必须指定context的数据类型
};
render(){
return(
<button style={{background: this.context.color }}></button>
)
}
}
// 父组件
class Message extends Component{
constructor( props ){
super( props );
};
// 父组件必须要定义 childContextTypes 和 getChildContext()

childContextTypes = {
color: React.PropTypes.string
};
getChildContext(){
return {color: "red"};
};

render(){
return(
<div>
<Button />
</div>
)
}
}

父组件添加 childContextTypes 和 getChildContext(),React自动向下传递数据然后在组件中的任意组件都能通过定义 contextTypes(必须指定context的数据类型) 访问 context 中的数据。

3. 子组件向父组件传递信息

主要是依赖 props 来传递事件的引用,并通过回调的方式来实现

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
// 子组件
class Button extends Component{
handleClickBtn(){
var _num = this.props.number + 1;
this.props.callback( _num );
//子组件将改变后的数据传递给父组件的回调函数来实现传递信息
};
render(){
return(
<button onClick={this.handleClickBtn.bind(this)}></button>
)
}
}
// 父组件
class Message extends Component{
constructor( props ){
super( props );
this.state ={
number : 0
}
};

handleChangeNumber( _number ){
this.setState({
number: _number
})
};

render(){
return(
<div>
<span>点击增加:{this.state.number} </span>
<Button number={this.state.number} callback={this.handleChangeNumber}/>
</div>
)
}
}

4. 没有任何嵌套关系的组件之间传值(兄弟组件之间传值)

主要是依赖 第三方组件来实现兄弟组件之间的传值

5. 利用react-redux进行组件之间的状态信息共享

baishiwen wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!