单个插槽
假设有一个名为Box
的子组件
...
<Box>
<div>123123</div>
</Box>
...
// 在子组件中
...
render() {
return (
<div>
<div>xxx....</div>
{this.props.children}
</div>
)
}
/** 输出
* <div>xxx....</div>
* <div>123123</div>
*/
多个插槽
在父级的子组件节点(<Box>...</Box>
)中,写多个div
就是多个插槽,在子组件中,this.props.children
是一个数组,直接写this.props.children
的话会把所有的插槽都放在节点上
...
<Box>
<div>123123</div>
<div>aaabbbccc</div>
</Box>
...
// 在子组件中
...
render() {
return (
<div>
<div>xxx....</div>
{this.props.children}
</div>
)
}
/** 输出
* <div>xxx....</div>
* <div>123123</div>
* <div>aaabbbccc</div>
*/
因为this.props.children
是一个数组,如果想要区分开,可以使用{this.props.children[0]}
...
render() {
return (
<div>
<div>xxx....</div>
{this.props.children[1]}
</div>
)
}
/** 输出
* <div>xxx....</div>
* <div>aaabbbccc</div>
*/
也可以将插入的div添加个标识符
...
<Box>
<div ref="title" name="title">111</div>
<div ref="content" name="content">222</div>
</Box>
...
我们会发现,组件中接收的值有ref和name属性(用别的属性也可以,在这里只是用ref和name举一个栗子)
在使用时候,可以直接输出this.props.children.filter(item => item.ref === 'content')
就可以得到想要的了
注意事项
在插槽子组件中使用filter
时有一个坑,就是我们做组件时,插槽的位置是可填可不填的,而在react中如果只填写一个插槽的话,this.props.children
并不是一个数组,所以会导致filter
报错
可以在输出时写成这种方式:
...
{this.props.children && this.props.children.length ? this.props.children.filter(item => item.ref === 'content') : this.props.children}
...