【问题标题】:How to use React + TypeScript to render components by looping through an array?如何使用 React + TypeScript 通过遍历数组来渲染组件?
【发布时间】:2019-10-24 20:11:25
【问题描述】:

我试图循环遍历数组的项目,但我在 TypeScript 中缺少一些我的组件的类型。我已经尝试过Card<anyCard<IProps> 的接口在下面定义(下面没有使用)。

这是我目前遇到的错误 我收到此错误。

键入'{键:数字;卡:{名称:字符串;图片:字符串;身份证号码; }; }' 不可分配给类型 'IntrinsicAttributes & { children?: 反应节点; }'。 'IntrinsicAttributes & { children?: ReactNode; 类型上不存在属性 'card' }'。

我很想知道我在这里错过了什么?

const cards = [
  {
    name: "a",
    image: "red",
    id: 1
  },
  {
    name: "b",
    image: "blue",
    id: 2
  },
  {
    name: "c",
    image: "green",
    id: 3
  }
];

interface IProps {
  card: {
    name: string;
    image: string;
    id: number;
  };
  key: string;
}


...(Stateless component logic here)...

const renderCards = () => {
    return cards.map(card => {
      return <Card key={card.id} card={card} />;
    });
  };

  return (
    <div>

      <CardContainer>{renderCards()}</CardContainer>
    </div>
  );

【问题讨论】:

  • 您的 Card 组件是否接受 card 属性?

标签: reactjs typescript


【解决方案1】:

我需要查看您的 Card 组件实现,但我猜以下内容应该会有所帮助:

interface ICard {
  name: string;
  image: string;
  id: number;
}

interface IProps {
  card: ICard;
  key: string;
}

const cards: ICard[] = [
  {
    name: "a",
    image: "red",
    id: 1,
  },
  {
    name: "b",
    image: "blue",
    id: 2,
  },
  {
    name: "c",
    image: "green",
    id: 3,
  },
];

const Card: React.FC<{ card: ICard }> = ({ card }) => {
  return <div>{card.name}</div>;
};

const renderCards = () => {
  return cards.map(card => {
    return <Card key={card.id} card={card} />;
  });
};

return (
  <div>
    <CardContainer>{renderCards()}</CardContainer>
  </div>
);

【讨论】:

    【解决方案2】:

    确保在 Props 的界面中包含 children 参数

    例如

    interface CardProps {
    card:{
        name: string;
        image: string;
        id: number;
      },
      children: React.ReactNode
    }
    
    
    const Card= ({
      card,
      children,
    }: CardProps) => {
    // and do whatever you like with `card` prop here
    return ( {children})
    }
    
    

    【讨论】:

    • @Kim Lee 做了任何回答帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2022-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2016-03-05
    相关资源
    最近更新 更多