Skip to content

react 插槽设计

痛点

  • 在编写组件的时候,插槽可以先进行占位,在渲染的时候将插槽渲染到某一个位置,很遗憾的是 react 没有这个设计,需要自己去实现

思路

  • 1、为ReactElement虚拟 DOM加一个slot的属性
  • 2、首先在父组件中获取到 props.children子的ReactElement,并且转换成数组
  • 3、遍历数组,把 ReactElement 的 slot 作为 key,绑定一个 map 映射 key 对应一个 ReactElement,如果没有 slot key 就是 default
  • 4、最后从 map 中取出对应的 ReactElement,渲染在页面,实现插槽的效果
js
const useSlot = (props) => {
  let childrens = [];
  if (props.children) {
    if (Array.isArray(props.children)) {
      childrens = props.children;
    } else {
      childrens = [props.children];
    }
  }
  let slotMap = {};
  childrens.forEach((children) => {
    slotMap[children.props.slot || "default"] = children;
  });
  return slotMap;
};

function Layout(props) {
  const slot = useSlot(props);
  return (
    <>
      {slot.head}
      {slot.middle}
      {slot.tail}
      {slot.default}
    </>
  );
}

export default function AppSlot() {
  return (
    <>
      <Layout>
        <h1>默认</h1>
        <h1 slot="head">头部</h1>
        <h1 slot="middle">中间</h1>
        <h1 slot="tail">尾部</h1>
      </Layout>
    </>
  );
}

reactSolt