[英]How do I pass an array of objects that contains a component to child component in React with Typescript?
I need to make Accordion component reusable.我需要使 Accordion 组件可重复使用。 In the future I should be able to add new object to the same array 'accordionProps' and pass it down to accordion.
将来我应该能够将新的 object 添加到同一个数组 'accordionProps' 并将其传递给手风琴。
Here I'm passing an array 'accordionProps' of objects down to component.在这里,我将对象数组“accordionProps”传递给组件。 Prop types are defined in child component Accordion which matches my array content.
道具类型在与我的数组内容匹配的子组件 Accordion 中定义。
const accordionProps = [
{
title: 'Active Orders',
body: <OrderModule />,
},
{
title: 'Drivers',
body: <DriverModule />,
},
];
return (
<DashboardWrapper>
<Accordion title={title} body={body}/>
<Map />
</DashboardWrapper>
);
};
export default Dashboard;
Still TypeScript throws an error: Type '{ accordionProps: { title: string;仍然 TypeScript 抛出错误:Type '{accordionProps: { title: string; body: Element;
身体:元素; }[];
}[]; }' is not assignable to type 'IntrinsicAttributes & accordionProps'.
}' 不可分配给类型 'IntrinsicAttributes & AccordionProps'。 Property 'accordionProps' does not exist on type 'IntrinsicAttributes & accordionProps'.
“IntrinsicAttributes & AccordionProps”类型不存在属性“accordionProps”。
It doesn't work when I do pass props as {...accordionProps} either.当我将道具作为 {...accordionProps} 传递时,它也不起作用。
Here is what my child component Dashboard looks like:这是我的子组件仪表板的样子:
import { Component } from 'react';
type accordionProps = [
{
title: string;
body: Component;
},
];
const Accordion = (props: accordionProps) => {
return (
<AccordionContainer>
{props.map(section => (
<div key={section.title}>
<div>{section.title})</div>
<div>{section.body}</div>
</div>
))}
</AccordionContainer>
);
};
export default Accordion;
I can't figure why TS is not letting me do that.我不明白为什么 TS 不让我这样做。
Does anyone know if an abstraction like that is even possible in React?有谁知道在 React 中是否可以实现这样的抽象?
Help is really appreciated.非常感谢您的帮助。
You declared your prop types as an array with one object in it:您将道具类型声明为一个数组,其中包含一个 object:
type AccordionProps = [
{
title: string;
body: Component;
},
];
However, react props must be an object:但是,react props 必须是 object:
type AccordionProps = {
title: string;
body: Component;
},
Then, in order to render an array of items, you need to map over the array of props, rendering the component you want in each iteration of the loop.然后,为了渲染一个项目数组,你需要 map 覆盖 props 数组,在循环的每次迭代中渲染你想要的组件。
For example, assuming you had:例如,假设您有:
// declare an array of AccordionProps objects
const accordionProps: AccordionProps[] = [
{
title: 'Active Orders',
body: <OrderModule />,
},
{
title: 'Drivers',
body: <DriverModule />,
},
];
Then you might render those like so:然后你可能会像这样渲染:
<>
{ accordionProps.map(props => <Accordion {...props} />) }
</>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.