【发布时间】:2022-01-11 20:55:30
【问题描述】:
我在 React 中创建了一个“InfoList”组件,我想通过一个对象数组作为道具传递,然后以列表类型格式映射结果,唯一的问题是数组是从 API 和键中获取的将根据传递给 API 的特定 URL 具有不同的名称。我觉得好像泛型是这里的答案,并尝试过这种方法,但不断收到语法错误
interface IInfoList {
title: string;
arr: {
//want the key here to be generic
key: string;
}[]; }
export const InfoList = (props: IInfoList) => {
return (
<Row className="align-items-start">
<Col lg={1}>
<h5>{props.title}:</h5>
</Col>
<Col>
{props.arr.slice(0, 6).map((item, i) => {
//Generic key accessed via "item" here
return <p className="pr-1 mb-0 d-inline" key={i}>{`${item.key}, `}</p>;
})}
</Col>
</Row>
); };
我是 typescript 和泛型概念的新手,如果这很明显,我很抱歉,但是有人有什么想法吗?
【问题讨论】:
-
您能否举例说明您将从 api 收到的数据的形式。例如。 {title: 'Hi', arr: [{key: 'a'}]} “key”会根据对 API 的调用而有所不同吗?编译时是否知道不同的变体?
标签: reactjs typescript interface react-component