react18 实现具名插槽

效果预览

技术要点

当父组件给子组件传递的 JSX 超过一个标签时,子组件接收到的 children 是一个数组,通过解析数组中各 JSX 的属性 slot ,即可实现具名插槽的分发!

代码实现

Father.jsx

js 复制代码
import Child from "./Child";

export default function Father() {
  return (
    <div>
      <Child>
        <h2 slot="title">标题</h2>
        <p slot="content">内容</p>
      </Child>
    </div>
  );
}

Child.jsx

js 复制代码
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;
相关推荐
Bulut090723 天前
Vue的slot插槽(默认插槽、具名插槽、作用域插槽)
vue.js·具名插槽·slot插槽·默认插槽·作用域插槽