学过vue的话,对插槽并不陌生,react的插槽和vue的有几分类似
举例1-匿名插槽
Father.jsx
import React,{Component, Suspense} from 'react'
import Children from './Children'
export default class Father extends Component{
constructor(props){
super(props)
this.state={
}
}
render (){
return (
console.log('ppp')}>
p1p1p1p1p1p1pp1p1p11p1pp11
h2h2h2h2h2hh2h2
)
}
}
Children.jsx
import React,{Component} from 'react'
import Grandson from './Grandson'
import { ThemeContext,UserContext } from "./Father";//引入父组件的Consumer容器
export default class Children extends Component{
constructor(props){
super(props)
this.state={
}
}
render (){
return (
{
Array.isArray(this.props.children) ? this.props.children.map((item,index)=>{
return item
}) : this.props.children
}
)
}
}
以上react代码就像是vue的匿名插槽,但是react中,被组件包裹的子标签(孙及以下不算),每一个都会在组件中的this.props.children中,只有一个的话this.props.children为单个元素对象,多个的话为数组
举例2-具名插槽 Father.jsximport React,{Component, Suspense} from 'react'
import Children from './Children'
export default class Father extends Component{
constructor(props){
super(props)
this.state={
}
}
render (){
return (
p1p1p1p1p1p1pp1p1p11p1pp11
h2h2h2h2h2hh2h2
)
}
}
Children.jsx
import React,{Component} from 'react'
import Grandson from './Grandson'
import { ThemeContext,UserContext } from "./Father";//引入父组件的Consumer容器
export default class Children extends Component{
constructor(props){
super(props)
this.state={
}
}
render (){
let children = Array.isArray(this.props.children) ? this.props.children : [this.props.children];
const slots = children.reduce((slots,item)=>{
slots[item.props.slot] = item
return slots
}, {})
return (
{slots['hView']}
{slots['pView']}
)
}
}