在React中作为prop传递组件,并作为JSX标签调用它们



假设我有一个包装器组件:

// wrapper that renders component passed as a prop
const Component = (childrenComponent) => <div>{childrenComponent}</div>

我想做的是在一些页面中调用组件,如:

import React from 'react'
const Page = () => {
const ChildrenComponent = () => <div>Children Component</div>
return <Component childrenComponent={ChildrenComponent} />
}

这将工作得很好。我的问题是,假设道具名称应该是小写的,我如何改变包装组件代码,以便能够以JSX的方式调用childcomponent(而不是内联的{childcomponent}),同时满足PascalCase中命名react组件的要求:

// this will not work
const Component = (childrenComponent) => <div><childrenComponent /></div>
// this will work but the prop name isn't camelCase
const Component = (ChildrenComponent) => <div><ChildrenComponent /></div>

您可以这样设置Component:

const Component = props => {
return (
<div>{props.children}</div>
)
}

使用Component:

<Component>
<ChildrenComponent/>
</Component>

来自文档的更多阅读材料

cloneElement的用法如下:

const Component = (children, ...props) => {
const clonedChild = cloneElement(children(), props)
return <>{clonedChild}</>
}

您需要将返回的结果包装到一个片段中。

最新更新