1. 父组件向子组件通信
,子组件通过**this.props.*****与父组件通信,
//父组件,将时间传递给子组件
import React,{Component} from 'react';
import Children from './App';
class Parent extends Component{
constructor(props){
super(props);
this.state={
date : `${new Date().getHours()}:
${new Date().getMinutes()}:
${new Date().getSeconds()}`
}
}
render(){
return(
<div>
<Children date = {this.state.date}/>
</div>
)
}
}
export default Parent;
//子组件
import React,{Component} from 'react';
class Children extends Component{
constructor(props){
super(props)
}
render(){
return(
<div>
<span>{this.props.date}</span>
</div>
)
}
}
export default Children;
2.子组件向父组件通信
子组件向父组件通信一般用回调函数,父组件事先定义好回调函数。并将回调函数传递给子组件,子组件调用回调函数,向父组件通信。
//父组件
import React,{Component} from 'react';
import Children from './App';
class Parent extends Component{
constructor(props){
super(props);
this.state={
index : 0
}
}
getNumCallback = (num) => {
this.setState({
index :num
})
alert(this.state.index)
}
render(){
return(
<div>
<Children
date = {this.state.date}
getNumCallback = {this.getNumCallback.bind(this)}
/>
</div>
)
}
}
export default Parent;
//子组件
import React,{Component} from 'react';
class Children extends Component{
constructor(props){
super(props);
this.state = {
num : 0
}
}
numClickHander = ()=>{
this.props.getNumCallback(this.state.num+1)
this.setState({
num:this.state.num +1
})
}
render(){
return(
<div>
<button onClick = {this.numClickHander.bind(this)}>{this.state.num}</button>
</div>
)
}
}
export default Children;