You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数组件是否支持向{children}插槽传递自定义props?

React 父组件向嵌套children传递props的实现问题与方案

问题描述

问题解决方案见正文底部。

我尝试通过{children}向子组件传递props,现有代码如下:

父组件FatherComp:

const FatherComp = ({ children, propsToPassToChild }) => (
    <div>Dynamic component content: 
        {children}
    </div>
)

子组件ChildComp:

const ChildComp = ({ childProps }) => <p>This is the dynamic content</p>

当前调用方式:

<FatherComp>
    <ChildComp/> // 此处无法直接给ChildComp传参,因为它嵌套在FatherComp内部
</FatherComp>

我希望在FatherComp内部渲染{children}的位置直接向ChildComp传递propsToPassToChild参数:

const FatherComp = ({ children, propsToPassToChild }) => (
    <div>Dynamic component content: 
        >>>>>> {children} <<<<<< *此处需要给children传递props* 
    </div>
)

请问不借助状态管理工具的前提下,仅使用React函数组件能否直接实现该需求?


可行解决方案

后续在实际项目中遇到同类问题时,找到了可落地的实现方案:

const Father = ({ child }) => {
    return (
        <div>
            {child({ text: 'I am props from father' })}
        </div>
    );
};

const Child = ({ text }) => {
    return (
        <div>Hey there {text}</div>
    );
};

Father组件的调用方式:

const App = () => <Father child={Child} />

只需将子组件作为返回组件的函数传入父组件的props即可,虽然不算「直接」的解决方案,但无需将子组件包裹在父组件内部即可解决问题。


内容的提问来源于stack exchange,提问作者Niv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:15:08