react如何实现插槽
React 实现插槽的方法
React 本身没有直接提供类似 Vue 的插槽(slot)概念,但可以通过以下几种方式实现类似功能:
使用 props.children
React 组件可以通过 props.children 获取组件标签之间的内容,这是最简单的插槽实现方式。

function Card(props) {
return <div className="card">{props.children}</div>;
}
function App() {
return (
<Card>
<h1>标题</h1>
<p>内容</p>
</Card>
);
}
使用命名 props
通过自定义 props 实现命名插槽的效果,可以更灵活地控制插槽位置。
function Layout(props) {
return (
<div>
<header>{props.header}</header>
<main>{props.main}</main>
<footer>{props.footer}</footer>
</div>
);
}
function App() {
return (
<Layout
header={<h1>页眉</h1>}
main={<p>主要内容</p>}
footer={<div>页脚</div>}
/>
);
}
使用 React.cloneElement
当需要向插槽内容传递额外 props 时,可以使用 React.cloneElement。

function Tabs(props) {
const [activeIndex, setActiveIndex] = useState(0);
return (
<div>
{React.Children.map(props.children, (child, index) =>
React.cloneElement(child, {
isActive: index === activeIndex,
onClick: () => setActiveIndex(index)
})
)}
</div>
);
}
使用 Context API
对于深层嵌套的组件插槽,可以结合 Context API 实现。
const SlotContext = createContext();
function SlotProvider(props) {
const [slots, setSlots] = useState({});
return (
<SlotContext.Provider value={{ slots, setSlots }}>
{props.children}
</SlotContext.Provider>
);
}
function Slot(props) {
const { setSlots } = useContext(SlotContext);
useEffect(() => {
setSlots(prev => ({ ...prev, [props.name]: props.children }));
}, [props.children]);
return null;
}
function SlotContent({ name }) {
const { slots } = useContext(SlotContext);
return slots[name] || null;
}
使用 render props 模式
通过函数作为 prop 的方式实现更灵活的插槽逻辑。
function DataFetcher({ render }) {
const [data, setData] = useState(null);
useEffect(() => {
fetchData().then(setData);
}, []);
return render(data);
}
function App() {
return (
<DataFetcher
render={data => data ? <div>{data}</div> : <p>加载中...</p>}
/>
);
}
这些方法可以根据具体场景灵活组合使用,React 的插槽实现相比 Vue 更灵活但也需要更多手动控制。






