插槽
小于 1 分钟约 243 字
import React from 'react'
import ReactDOM from 'react-dom/client'
import DemoOne from './views/DemoOne'
import DemoTwo from './views/DemoTwo'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<>
<DemoOne
title='我是标题'
x={10}
className='box'
style={{ fontSize: '20px' }}
>
<span>哈哈哈哈哈哈哈哈哈</span>
<span>呵呵呵呵呵呵呵</span>
</DemoOne>
<DemoOne
title='我是标题'
x={10}
className='box'
style={{ fontSize: '20px' }}
>
<span>12312312312312</span>
</DemoOne>
<DemoOne title='我是标题'></DemoOne>
<DemoTwo>
<span slot='footer'>我是页脚</span>
<span slot='header'>我是页眉</span>
</DemoTwo>
</>
)
import PropTypes from 'prop-types'
import React from 'react'
const DemoOne = function DemoOne(props) {
let { className, style, title, x, children } = props
console.log(x)
children = React.Children.toArray(children)
console.log(children)
return (
<div className={`demo-box ${className}`} style={style}>
我是DemoOne
<h2>{title}</h2>
{children[0]}
<br />
{children[1]}
</div>
)
}
// 设置默认值
DemoOne.defaultProps = {
x: 0,
}
//规则校验
DemoOne.propTypes = {
title: PropTypes.string.isRequired,
x: PropTypes.number,
}
export default DemoOne
import React from 'react'
const DemoTwo = function DemoOne(props) {
let { children } = props
children = React.Children.toArray(children)
let headerSlot = []
let footerSlot = []
let defaultSlot = []
children.forEach((child) => {
let { slot } = child.props
if (slot === 'header') {
headerSlot.push(child)
} else if (slot === 'footer') {
footerSlot.push(child)
} else {
defaultSlot.push(child)
}
})
return (
<div className='demo-box'>
{headerSlot}
<br />
{footerSlot}
</div>
)
}
export default DemoTwo