react实现具名插槽

63 阅读1分钟

具名插槽

react 中是没有插槽的概念的,怎么使用vue的具名插槽

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 (
            <div>
              <Children>
                  <div slot="pView">
                      <p>p1p1p1p1p1p1pp1p1p11p1pp11</p>
                    </div>
                    <div slot="hView">
                      <h2>h2h2h2h2h2hh2h2</h2>
                    </div>
                </Children>
            </div>
        )
    }
}

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 (
            <div>
               {slots['hView']}
	       {slots['pView']}
            </div>
        )
    }
}