兄弟通信
自定义Hook/ localStorage
redux
兄弟组件
子传给父,父再传给另一个子
子组件1
class Children1 extends Component{
constructor(props){
super(props);
}
handerClick(){
this.props.changeChild2Color('skyblue')
// 改变兄弟组件的颜色 把changeChild2Color的参数传给父
}
render(){
return(
<div>
<div>children1</div>
<button onClick={(e)=>{this.handerClick(e)}}>改变children2背景</button>
</div>
)
}
}
父组件
class Father extends Component{
constructor(props){
super(props)
this.state = {
child2bgcolor:'pink'
}
}
onchild2bgChange(color){
this.setState({
child2bgcolor:color
})
}
render(props){
<div>
<Children1 changeChild2Color={(color)=>{this.onchild2bgChange(color)}} />
<Children2 bgcolor={this.state.child2bgcolor} />
</div>
}
}
子组件2
class Children2 extends Component{
constructor(props){
super(props);
}
render(){
return(
<div style={{background:this.props.bgcolor}}> // 从父元素获取自己的背景色
<div>children2 背景色 {this.props.bgcolor}</div> // children2 背景色 skyblue
</div>
)
}
}