React学习笔记四——插槽

103 阅读1分钟

image.png

插槽的作用

和属性一样,都是想办法让组件具备更强的复用性

传递数据用属性props
传递HTML结构用插槽

React中有专门针对父组件传过来HTML结构的处理的函数:React.Children,对props.children做处理,count/forEach/map/toArray

具名插槽

//父组件
    <DemoOne title='我是标题' x={10} className='box'>
      <span slot='head'>我是第二个内容</span>   //这里的slot是我们定义的名字并不是vue中规定只能为slot。
      <span slot='foot'>我是第一个内容</span>
    </DemoOne>
//函数子组件
import PropTypes from 'prop-types'
import React from 'react'
const DemoOne = (props) => {
  let { title,x,children } = props
  children = React.Children.toArray(children)//保证一定为数组
  let headContent 
  let footContent=[]
  children.forEach(child => {
    let { slot } = child.props //重点!children里保存的是虚拟Dom信息,属性信息保存在props里,可以解构出来判断。
    if (slot === 'head') {
      headContent=child
    } else if (slot === 'foot') {
      footContent.push(child)
    }
  })
  return <div>{title}<br></br>
    {headContent}
    <div>{x}</div>
    {footContent}
  </div>

}
// 通过把函数当做对象,设置静态的私有属性方法,来给其设置属性的校验规则
DemoOne.defaultProps = {
   x:0  //没有传值默认值
}
//校验规则
DemoOne.propTypes = {
  title: PropTypes.string.isRequired,//必传 字符串
  x:PropTypes.number //数字
 }
export default DemoOne