效果预览
技术要点
当父组件给子组件传递的 JSX 超过一个标签时,子组件接收到的 children 是一个数组,通过解析数组中各 JSX 的属性 slot ,即可实现具名插槽的分发!
代码实现
Father.jsx
import Child from "./Child"; export default function Father() { return ( <div> <Child> <h2 slot="title">标题</h2> <p slot="content">内容</p> </Child> </div> ); }
Child.jsx
function Child({ children }) { let slotDic = {}; if (Array.isArray(children)) { children.forEach((child) => { let slotName = child.props.slot; if (slotName) { slotDic[slotName] = child; } }); } return ( <div> <h1>子组件</h1> {slotDic.title} {slotDic.content} </div> ); } export default Child;