React 渲染特定的子项

问题描述 投票:0回答:6

我浏览了其他人与此相关的问题,但找不到合适的答案。我想将子项传递给组件,然后在我想要的位置提取特定的子项,我见过的大多数示例只是将子项渲染在同一个位置。

我的组件看起来像这样 -

<ParentComponent>

<ChildOne/>
<ChildTwo/>

<ParentComponent/>

当我在父组件中记录 props.children 时,我得到一个数组,其中包含两个子组件作为对象。有没有一种简单的方法可以在我需要的地方拉出特定的子项,例如目前我正在使用

{props.children.ChildOne}
,这并不理想,因为我们将动态传递子项 将来数组长度可能会改变。
一如既往,非常感谢任何帮助!

reactjs children
6个回答
1
投票
props.children[0]

道具更有意义。然后你可以按照你喜欢的方式渲染它们。

children

但是了解您的确切场景将有助于概念化实现这一点的最佳方法。也许您可以重构代码以避免传递这样的子数组。


1
投票
<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



0
投票

<ParentComponent> <ChildTwo/> <ChildOne/> <ParentComponent/>

 API 在这里并没有什么用处。
你可以这样做:

ReactChildren



0
投票

无论使用父组件:

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/>



0
投票

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>) }



-1
投票
<ParentComponent someComponent={<div>Testing</div>}> <div>testing children component</div> </ParentComponent>

及其

ParentComponent
的组件中的状态/props/redux 存储管理来控制传递给
ParentComponent
的子组件。
但是为了根据您的用例找到解决方案,我们可以避免使用 

children

属性并在

children
上使用我们定义的属性。
ParentComponent

所以,我们现在可以根据键进行过滤。

查看这个

演示

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.