react组件通讯

父组件给子组件传

父组件在ReactDOM的render中当作属性传给子组件

1
2
3
4
5
6
7
{/* father */}
var arr=[1,2,3,4,5,6,7,8,9]
render(){
return <div>
<Son {...arr}></Son>
</div>
}

1
2
3
4
5
6
7
8
9
10
11
12
class Son extends React.component {
constructor(props){
super()
this.setState(props)
}
setState(props){
this.props=props
}
render(){
return <div>父组件传来的数据:{this.props}</div>
}
}

子组件给父组件传

父组件在ReactDOM的render中把一个方法当作属性传给子组件

1
2
3
4
5
6
7
8
9
10
11
{/* father */}
var arr=[1,2,3,4,5,6,7,8,9]
render(){
return <div>
<Son {...arr} sonFnName={this.fatherFn} ></Son>
</div>
}
fatherFn(arg){
//操作arg
//age===>this.props.age
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Son extends React.component {
constructor(props){
super()
this.setState(props)
//要传给父组件的数据
this.props.age=10
}
setState(props){
this.props=props
}
render(){
return <div>
父组件传来的数据:{this.props}
{/* 将当前节点挂载到this上 */}
<div ref='divTarget' onClick={()=>this.sonFn(this)}>父组件传来的方法名:{this.props.sonFnName}</div>
</div>
}
sonFn(arg){
this.props.sonFnName(arg)
}
}