react实现默认插槽以及具名插槽
学过vue的话,对插槽并不陌生,react的插槽和vue的有几分类似举例1-匿名插槽Father.jsximport React,{Component, Suspense} from 'react'import Children from './Children'export default class Father extends Component{constructor(props){sup
·
学过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 (
<div>
<Children>
<div onClick={()=>console.log('ppp')}>
<p>p1p1p1p1p1p1pp1p1p11p1pp11</p>
</div>
<div>
<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 (){
return (
<div>
{
Array.isArray(this.props.children) ? this.props.children.map((item,index)=>{
return item
}) : this.props.children
}
</div>
)
}
}
以上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 (
<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>
)
}
}
更多推荐
已为社区贡献3条内容
所有评论(0)