React中插槽处理机制
需求:假如底部可能有按钮,根据需求判断需要展示或不展示,或者需要展示不同的按钮或者其他DOM
 解决1:需要的按钮可以在组件中写死,后期基于传递进来的属性来进行判断
 解决2:我们也可以把按钮的区域预留出来,但是内容不写,内容让调用的组件的时候,把东西传递进来【传递的是结构】
<DemoOne>
   <div>1</div>
   <div>2</div>
</DemoOne>
 
组件中的两个div基于props.children获取传递的子节点信息
 这一套机制就是插槽机制
 调用组件的时候,基于上闭合调用方式把插槽信息【子节点信息】,传递给组件,组件内部渲染即可
例子1(匿名插槽):
 传进来的子节点若只有一个展示在组件头部,若两个则第一个节点在组件头部,第二个节点在组件底部
//父组件
 <div>
            <h1>没有children</h1>
            <DemoOne/>
            <h1>一个节点</h1>
            <DemoOne>
                <div>1</div>
            </DemoOne>
            <h1>两个节点</h1>
            <DemoOne>
                <div>1</div>
                <div>2</div>
            </DemoOne>
</div>
//子组件
const DemoOne=(props)=>{
    let {x,children}=props
    //使用React中的方法将children转换为数组
    children=React.Children.toArray(children)
    return(
        <div>
            {children[0]}
            <div>DomeOne</div>
            {children[1]}
        </div>
    )
}
 
运行结果:
 
 缺点:匿名插槽,两个节点的顺序不能改变,必须按照指定顺序
例子2(具名插槽):
//子组件
const DemoOne=(props)=>{
    let {x,children}=props
    //使用React中的方法将children转换为数组
    children=React.Children.toArray(children)
    let headerSlot=[],
        footerSlot=[],
        defaultSlot=[]
    children.forEach(child=>{
        let {slot}=child.props
        console.log(slot,child)
        if(slot==='header'){
            headerSlot.push(child)
        }else if(slot==='footer'){
            footerSlot.push(child)
        }else {
            defaultSlot.push(child)
        }
    })
    return(
        <div>
            {headerSlot}
            <div>DomeOne</div>
            {defaultSlot}
            {footerSlot}
        </div>
    )
}
//父组件中调用
<DemoOne>
     <div slot='footer'>我在底部</div>
      <div slot='header'>我在头部</div>
      <div>我是默认</div>
</DemoOne>
 

 具名插槽把筛选出的插槽信息放在指定位置进行渲染
 目的:在调用组件的,传递信息的时候,可以不用



















