一、父组件传递数据给子组件
1.父组件提供要传递的state数据
2.给子组件标签添加事件,值为state中的数据
3.子组件中通过props接收父组件中传递的数据
//父组件
class Parent extends React.Component{
state={
lastName:'王'
}
render(){
return(
<div className="parent">
父组件:
<Child name={this.state.lastName} />
</div>
)
}
}
//子组件
const Child=(props)=>{
return (
<div className="child">
<p>子组件,接收到父组件的数据:{props.name}</p>
</div>
)
}
二、子组件传递数据给父组件
思路:利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数
1.父组件提供一个回调函数(用于接收数据)
2.将该函数作为属性的值,传递给子组件
3.子组件通过props调用回调函数
4.将子组件的数据作为参数传递给回调函数
//父组件
class Parent extends React.Component{
state={
parentMsg:''
}
//提供回调函数,用来接收数据
getChildMsg=data=>{
console.log('接收到子组件中传来的数据'+data)
this.setState({
parentMsg:data
})
}
render(){
return(
<div className="parent">
父组件:{this.state.parentMsg}
<Child getMsg={this.getChildMsg} />
</div>
)
}
}
//子组件
class Child extends React.Component {
state={
msg:'玩手机'
}
handleClick=()=>{
//子组件调用父组件中传递过来的回调函数
this.props.getMsg(this.state.msg)
}
render(){
return (
<div className="child">
子组件:<button onClick={this.handleClick}>点我,给父组件传递数据</button>
</div>
)
}
}
三、兄弟组件
将共享状态提升到最近的公共父组件中,由公共父组件管理这个状态
思想:状态提升
公共父组件职责:1.提供共享状态 2.提供操作共享状态的方法
要通讯的子组件只需通过props接收状态或操作状态的方法
//父组件
class Counter extends React.Component{
//提供共享状态
state={
count:0
}
//提供修改状态的方法
onIncrement=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
return (
<div>
<Child1 count={this.state.count} />
<Child2 onIncrement={this.onIncrement} />
</div>
)
}
}
const Child1=(props)=>{
return <h1>计数器:{props.count}</h1>
}
const Child2=(props)=>{
return <button onClick={props.onIncrement}>+1</button>
}