什么是 React Slots 模式?

React Slots 是一种组件组合模式,允许您将组件或 JSX 作为子项传递,并控制它们在组件不同部分的呈现方式。此模式的灵感来自 Vue.js 或 Web Components 等框架中的“插槽”。

React Slots 通常通过利用 **React context** 或 **child filters** 来实现,以创建命名插槽(`Title`、`Body`、`Footer`),以便父组件(如 `Card`)能够识别并正确呈现。以下是实现此目的的方法:

实现 React Slots

// Define the Card component and its slots
const Card = ({ children }) => {
  // Filter out specific child components based on their type
  const title = React.Children.toArray(children).find(child => child.type === Title);
  const body = React.Children.toArray(children).find(child => child.type === Body);
  const footer = React.Children.toArray(children).find(child => child.type === Footer);

  return (
    
{title}
{body}
{footer}
); }; // Slot components const Title = ({ children }) =>

{children}

; const Body = ({ children }) =>

{children}

; const Footer = ({ children }) =>
{children}
; // Usage const App = () => { return ( What is React? Learn React.
); };

解释

  • 卡片组件:收集子项并根据每个子项的类型属性进行过滤。通过将子项的类型与预定义的插槽组件进行比较来识别特定插槽(标题、正文、页脚)。
  • 插槽组件:Title、Body 和 Footer 充当占位符。它们是简单的组件,可直接渲染其子组件,但为 Card 组件提供语义含义。
  • 用法:子组件(标题、正文、页脚)是卡片内的插槽,可实现清晰且声明性的组合。
  • 输出 HTML

    上述设置呈现以下 HTML:

    What is React?

    Learn React.

    好处

  • 清晰的 API:使用标题、正文和页脚等语义插槽组件可提高代码的可读性。
  • 灵活性:无需修改 Card 组件即可重新排序、省略或扩展插槽。
  • 可重用性:此模式可用于任何需要命名插槽的组件。
  • 请发表评论👇您对这种模式及其用例有何看法。