您当前的位置: 首页 > 

【03】

暂无认证

  • 3浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

react实现默认插槽以及具名插槽

【03】 发布时间:2020-08-19 09:02:22 ,浏览量:3

学过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.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 (
            
          
                    
                      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']}
            
        )
    }
}
关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0639s