【问题标题】:REACT Passing array to child component反应将数组传递给子组件
【发布时间】:2019-01-02 16:31:21
【问题描述】:

我正在尝试学习如何使用 typescript 做出反应,但不确定为什么会收到此错误。

我有我的 CardApp:

public state = {
    cards: []
};


public render() {
    return (
        <div>
            <Form onSubmit={this.addNewCard}/>
            <CardList cards={this.state.cards}/>
        </div>
    );
}

卡片列表是:

const CardList = (props: ICard[]) => {
    return (
        <div>            
            { props.map((card: ICard) => <Card key={card.id} {...card} />) }   
        </div>
    )
}

这样我收到一个错误 Type '{ car​​ds: never[]; }' 不是 可分配给类型“IntrinsicAttributes & ICard[]”。输入'{卡: 绝不[]; }' 不可分配给类型 'ICard[]'。 类型“{卡:从不[]中缺少属性“长度”; }'。

但是,如果我创建一个 ICards 接口:

interface ICards {
    cards: ICard[]
}

然后使用 CardList 是:

const CardList = (props: ICards) => {
    return (
        <div>            
            { props.cards.map((card: ICard) => <Card key={card.id} {...card} />) }
        </div>
    )
}

这很好用,但我的印象是&lt;CardList cards={this.state.cards}/&gt; 传递的是数组而不是具有数组属性的对象,因此不需要ICards 接口。

【问题讨论】:

  • props 对象不是cards 数组,而是props 对象中的cards 键。你试过const CardList = (props: { cards: ICard[] })吗?
  • 是的,就是这样。我没有意识到它总是一个对象。谢谢你。如果你写并回答,我会接受。

标签: reactjs typescript visual-studio-code


【解决方案1】:

props 对象不是cards 数组,而是props 对象中的cards 键。

你可以这样写:

const CardList = (props: { cards: ICard[] }) => {
  return (
    <div>{props.map((card: ICard) => <Card key={card.id} {...card} />)}</div>
  );
};

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2020-01-22
    相关资源
    最近更新 更多