[英]How to pass props to children with functional components?
我在将道具传递给功能反应中的孩子时遇到了麻烦。 我的{children}
是一个Details
组件,如下所示:
<SidebarPage>
{children}
</SidebarPage>
const Details = () => {}
我怎样才能以这样的方式传递道具,我把道具放到{children}
并在Details
组件中收到这个道具? 这甚至可行吗?
谢谢你的帮助!
您可以将组件作为道具传递,例如 -
const SidebarPage = ({ChildComponent}) => {
const props = { name: "X" };
return <ChildComponent {...props} />
}
const Details = (props) => {}
<SidebarPage ChildComponent={Details} />
您可以使用 cloneElement 向组件子组件添加新道具
const newProps = {aProp: "aProp"} ;
return (
<SidebarPage>
{React.Children.map(props.children, child => {
return React.cloneElement(child, {
newProps,
}, null)
}
</SidebarPage>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.