react如何给插槽传参数
在React中给插槽传参的方法
React中没有Vue那样的具名插槽概念,但可以通过props.children或render props模式实现类似功能。以下是几种常用方法:
使用props.children传递内容
通过将子组件作为props.children传递,可以在父组件中控制子组件的渲染:
function ParentComponent() {
return (
<ChildComponent>
{(slotProps) => <div>接收到的参数: {slotProps.data}</div>}
</ChildComponent>
)
}
function ChildComponent({ children }) {
const slotProps = { data: '来自子组件的数据' }
return <div>{children(slotProps)}</div>
}
使用render props模式
这是一种更明确的插槽传参方式,通过props传递渲染函数:
function ParentComponent() {
return (
<ChildComponent
renderContent={(data) => <p>{data}</p>}
/>
)
}
function ChildComponent({ renderContent }) {
const data = '要传递的数据'
return <div>{renderContent(data)}</div>
}
使用Context API
对于深层嵌套的组件,可以使用Context共享数据:
const SlotContext = React.createContext()
function ParentComponent() {
return (
<ChildComponent>
<SlotContext.Consumer>
{(value) => <div>{value}</div>}
</SlotContext.Consumer>
</ChildComponent>
)
}
function ChildComponent({ children }) {
return (
<SlotContext.Provider value="上下文数据">
{children}
</SlotContext.Provider>
)
}
使用高阶组件
通过高阶组件包装可以实现更灵活的插槽逻辑:
function withSlot(Component) {
return function WrappedComponent(props) {
const slotData = '高阶组件数据'
return <Component {...props} slotData={slotData} />
}
}
选择哪种方法取决于具体场景。简单场景可用props.children,复杂交互建议使用render props或Context API。







