大家可以都了解在vue中插槽(slot)中的使用,slot在vue中是当作属性来使用的,但是在react中就截然不同了。
大家可以先了解一下下面的代码
`
import React, {Component} from 'react';
import Sidebar from "../01-base/Sidebar";
class Child extends Component{
render() {
return(
<div>
子组件
</div>
)
}
}
export default class App extends Component {
render() {
return (
<div>
<Child>
<div>
222
</div>
</Child>
</div>
);
}
}
其实也比较简单
但是大家可能发现在子组件中间的div里面的值222没有显示出来,那是因为在react解析render中的子组件时,直接Child整体组件替换了,也就没有222值了。
关于this.props.children的使用
this.props.children其实就相当于子组件将在父组件标签中间的值拿出来再次使用。
举一个例子:
import React, {Component} from 'react';
import Sidebar from "../01-base/Sidebar";
class Child extends Component{
render() {
return(
<div>
子组件
{this.props.children}
</div>
)
}
}
export default class App extends Component {
state = {
isShow: false
}
render() {
return (
<div>
<Child>
<div>
<button onClick={()=>{
this.setState({
isShow:!this.state.isShow
})
}
}>click</button>
</div>
</Child>
{this.state.isShow && <Sidebar/>}
</div>
);
}
}
结果:
关于React插槽的好处
1.减少了父子通信的次数
在APP组件使用时可以直接使用state状态,而不用进行父子通信了。
2.提高了组件的复用性