React中插槽处理机制

React中插槽处理机制

需求:假如底部可能有按钮,根据需求判断需要展示或不展示,或者需要展示不同的按钮或者其他DOM

解决1:需要的按钮可以在组件中写死,后期基于传递进来的属性来进行判断

解决2:我们也可以把按钮的区域预留出来,但是内容不写,内容让调用的组件的时候,把东西传递进来【传递的是结构】

html 复制代码
<DemoOne>
   <div>1</div>
   <div>2</div>
</DemoOne>

组件中的两个div基于props.children获取传递的子节点信息

这一套机制就是插槽机制

调用组件的时候,基于上闭合调用方式把插槽信息【子节点信息】,传递给组件,组件内部渲染即可

例子1(匿名插槽):

传进来的子节点若只有一个展示在组件头部,若两个则第一个节点在组件头部,第二个节点在组件底部

html 复制代码
//父组件
 <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(具名插槽):

javascript 复制代码
//子组件
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>

具名插槽把筛选出的插槽信息放在指定位置进行渲染

目的:在调用组件的,传递信息的时候,可以不用

相关推荐
kyriewen115 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
Timer@6 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫6 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81637 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan8 小时前
FastAPI -API Router的应用
前端·网络·python
走粥9 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0019 小时前
layui select重新渲染
前端·layui
weixin1997010801610 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化
九皇叔叔10 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity