组合方式:
1/直接嵌套的方式
2/组件以变量的形式放置
3/可以通过props值,以变量的形式相当于作为参数传递父组件,然后进行组合
import React,{Component} from 'react';
class ParentCom extends Component{
constructor(props){
super(props)
this.state={
childBg:'pink',
navCom: <NavCom />,
leftCom:<LeftCom />,
mainCom: <MainCom/>,
mainCom:props.changeMain ? props.changeMain:<Child4Com/>
}
this.changeCom= this.changeCom.bind(this)
}
render(){
// 父组件通过state
return(
<div>
<div className="nav">
{this.state.navCom}
</div>
<div className="left">
{this.state.leftCom}
</div>
<div className="main">
{this.state.mainCom}
</div>
<button onClick={this.changeCom}>更改组件</button>
</div>
)
}
changeCom(){
this.setState({
mainCom:<Child4Com/>
})
}
}
class NavCom extends Component{
render(){
return(
<div>
<h1>导航组件</h1>
</div>
)
}
}
class LeftCom extends Component{
render(){
return(
<div>
<h1>侧边内容组件</h1>
</div>
)
}
}
class MainCom extends Component{
render(){
return(
<div>
<h1>主要内容组件</h1>
</div>
)
}
}
class Child4Com extends Component{
render(){
return(
<div>
<h1>子组件4:判断父组件是否有传值,如果changeMain为空将mainCom改变后的组件4</h1>
</div>
)
}
}
export default ParentCom