检索循环中每个子元素的props,以使用一个值作为键反应



我有两个组件(为简单起见,我将它们称为<List/><ListItem/>),第二个组件在其道具之间包含id。我在<List/>组件内部有一个循环(见下文),我需要为我正在循环的listtiitems分配一个键。有一种方法来检索地图函数内的单个项目的id ?

//App.jsx
<List>
<ListItem id={adjsaiewwqa}/>
<ListItem id={adssandsadn}/>
</List>
//List.jsx
<div className="css-classes">
{props.children?.map(child => 
<div key={/*HERE I WANT TO INSERT LIST ITEM ID*/} className="other-css-classes">
{child}
</div>
}
</div>

编辑:这个问题出现了,因为我使用ReactNode[]作为孩子类型的反应道具。当子元素的内容是一个元素数组时,React。应该使用Elements[]。

之后,props就可以在子元素上正常调用了。

解决方案

你的List.jsx应该是:

<div className="css-classes">
{props.children?.map((child) => (
<div key={child.props.id} className="other-css-classes">
{child}
</div>
))}
</div>

如果你在使用typescript时遇到以下错误,那是因为子元素的类型应该是React.Element<MyPropsType>[]而不是React.ReactNode[]

Property 'props' does not exist on type 'string | number | boolean | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | ReactNodeArray | ReactPortal'.
Property 'props' does not exist on type 'string'.

相关内容

最新更新