react如何实现slot
在React中实现类似Vue的"slot"功能,可以通过以下几种方式实现:
使用props.children
React组件天然支持通过props.children获取子元素,这是最基础的插槽实现方式:

function ParentComponent(props) {
return <div className="parent">{props.children}</div>;
}
function App() {
return (
<ParentComponent>
<p>这是插入到slot中的内容</p>
</ParentComponent>
);
}
命名插槽模式
通过props传递React元素实现命名插槽:
function Layout({ header, content, footer }) {
return (
<div>
<header>{header}</header>
<main>{content}</main>
<footer>{footer}</footer>
</div>
);
}
function App() {
return (
<Layout
header={<h1>标题</h1>}
content={<p>正文内容</p>}
footer={<small>页脚</small>}
/>
);
}
使用render props
更灵活的插槽实现方式,可以传递函数作为插槽内容:

function DataFetcher({ render }) {
const data = fetchData(); // 获取数据
return render(data);
}
function App() {
return (
<DataFetcher
render={(data) => <div>{data}</div>}
/>
);
}
使用Context API
对于深层嵌套的组件,可以使用Context实现类似命名插槽的效果:
const SlotContext = React.createContext();
function Parent({ children }) {
const slots = {
header: children.find(child => child.type === Header),
content: children.find(child => child.type === Content)
};
return (
<SlotContext.Provider value={slots}>
<div className="parent">
{slots.header}
{slots.content}
</div>
</SlotContext.Provider>
);
}
使用React 18的新特性
React 18引入了更灵活的插槽模式:
function TabLayout({ left, right }) {
return (
<div className="tabs">
<div className="left-pane">{left}</div>
<div className="right-pane">{right}</div>
</div>
);
}
function App() {
return (
<TabLayout
left={<LeftContent />}
right={<RightContent />}
/>
);
}
每种实现方式各有优缺点,props.children适合简单场景,命名插槽更清晰但需要更多代码,render props最灵活但可能降低可读性,Context适合复杂层级结构。






