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
相关产品推荐
相关产品推荐

