【问题标题】:Typescript-React: Generic key when looping through array of objects defined in a props interfaceTypescript-React:循环遍历道具接口中定义的对象数组时的通用键
【发布时间】: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


【解决方案1】:

可以是这样的:

interface IInfoList<T> {
  title: string;
  arr: {
    //want the key here to be generic
    key: T;
  }[];
}

// extends unknown it's a hack to make the linter happy
export const InfoList = <T extends unknown>(props: IInfoList<T>) => {
  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>
  );
};

然后使用

const Parent = () => {
  return (
    <>
      <InfoList<number>
        title="Title"
        arr={[
          {
            key: 1,
          },
        ]}
      />
      <InfoList<string>
        title="Title"
        arr={[
          {
            key: '1',
          },
        ]}
      />
    </>
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2017-02-08
    相关资源
    最近更新 更多