首页 > 解决方案 > TSX 组件数组,数组内的组件

问题描述

我试图在 tsx 中有一个子组件数组,然后在这段代码中向数组中添加一个实例:

import ShoppingList from './ShoppingList';    
interface TPState {
  shoppingLists2: ShoppingList[];
  shoplistsums: number[];
  sum: number;
}

class TotalPrice extends React.Component<{}, TPState> {
  constructor(props: {}) {
    super(props);
    this.state = {
      shoppingLists2: [ShoppingList],
      sum: 0
    }
  }

但我收到一个错误,它是不可分配的。我正在使用数组在页面中的按钮按下时添加组件,并且我正在添加这样的初始项目。为什么是错的?

标签: reactjstypescripttypescomponents

解决方案


不确定您收到什么错误消息,可能是两件事。首先,您可以指定[ShoppingList]转换为类型。您还需要指定所有状态参数

class TotalPrice extends React.Component<{}, TPState> {
  public state = {
    shoppingLists2: [ShoppingList] as ShoppingList[], //  as ShoppingList[] may not be needed but dont know without the error message
    sum: 0,
    shoplistsums: [] // you were missing this item in your state, proabably what the issue was
  }
}

编辑:您需要为购物清单定义一个类型..而不是将其用作类型。

interface IShoppingList {
  someKey: number
  someOtherKey: string
}

那么你的状态类型

interface TPState {
  shoppingLists2: IShoppingList[];
  shoplistsums: number[];
  sum: number;
}

推荐阅读