我浏览了其他人与此相关的问题,但找不到合适的答案。我想将子项传递给组件,然后在我想要的位置提取特定的子项,我见过的大多数示例只是将子项渲染在同一个位置。
我的组件看起来像这样 -
<ParentComponent>
<ChildOne/>
<ChildTwo/>
<ParentComponent/>
当我在父组件中记录 props.children 时,我得到一个数组,其中包含两个子组件作为对象。有没有一种简单的方法可以在我需要的地方拉出特定的子项,例如目前我正在使用
{props.children.ChildOne}
,这并不理想,因为我们将动态传递子项
将来数组长度可能会改变。一如既往,非常感谢任何帮助!
props.children[0]
道具更有意义。然后你可以按照你喜欢的方式渲染它们。
children
但是了解您的确切场景将有助于概念化实现这一点的最佳方法。也许您可以重构代码以避免传递这样的子数组。
<ParentComponent childOne={ChildOne} childTwo={ChildTwo} />
...
const ParentComponent = ({ childOne, childTwo }) => {
return (
<div>
{childOne}
<div>
{childTwo}
</div>
</div>
);
};
属性,然后使用父组件中的
displayName
从子组件列表中查找特定的子组件,并将它们放置在您想要的位置。displayName
现在在父组件中,您可以使用其 displayName 过滤掉特定的子组件。
// define displayName for each component, it can be any string
// You can set the displayName for any react component before exporting as shown
// below
const ChildOne = (props) => { return (<div> Child One </div>)}
ChildOne.displayName = "ChildOne";
export default ChildOne;
const ChildTwo = (props) => { return (<div> Child Two </div>)}
ChildTwo.displayName = "ChildTwo";
export default ChildTwo;
就是这样,现在即使你将
const ParentComponent = (props) => {
const getChildByDisplayName = (displayName) => {
const child = React.Children.map(props.children, (child => {
// you can access displayName property by child.type.displayName
if (child.type.displayName === displayName) return child;
return null;
}))
return child;
}
return (
<div>
{/* You can change the order here as per your wish*/}
{getChildByDisplayName("ChildOne")}
{getChildByDisplayName("ChildTwo")}
</div>
)
}
放在
ChildTwo
之前,如下例所示,父组件仍然会先渲染 ChildOne
,然后渲染 ChildOne
,因为我们已经在父组件中定义了顺序。ChildTwo
import React from 'react';
import { ChildOne } from './YourFile';
export function ParentComponent({children}) {
return children.find(child => child.type === ChildOne)
}
<ParentComponent>
<ChildOne key="title"/>
<ChildTwo key="picture"/>
<ParentComponent/>
export default function ParentComponent(props: any) {
const title = props.children.find((o: any) => o.key === 'title')
const picture = props.children.find((o: any) => o.key === 'picture')
return <div>
<jumbobox>
{title}
</jumbobox>
<fancyframe>
{picture}
</fancyframe>
</div>
}
当您需要调用它时,您只需:
const ParentComponent = ({children, someComponent}:{children:React.ReactNode, someComponent:React.ReactNode}) => {
return (
<div>
{someComponent}
{children}
</div>)
}