什么是 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 }) => ;
// Usage
const App = () => {
return (
What is React?
Learn React.
);
};解释
输出 HTML
上述设置呈现以下 HTML:
What is React?Learn React.
好处
请发表评论👇您对这种模式及其用例有何看法。