reactjs - 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
}
}
但我收到一个错误,它是不可分配的。我正在使用数组在页面中的按钮按下时添加组件,并且我正在添加这样的初始项目。为什么是错的?
解决方案
不确定您收到什么错误消息,可能是两件事。首先,您可以指定[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;
}
推荐阅读
- javascript - 我的运营商出了什么问题?Javascript
- javascript - react-native - *.js 导入 *.ts 文件
- javascript - 在特定 url 上重定向 url
- javascript - 如何在网站中隐藏我的源文件以使用户无法访问
- javascript - 如何将包含多个重复关键字的字符串拆分为javascript中的数组?
- java - 编译器如何读取这个:someString.indexOf(someOtherString.charAt(0))?
- php - 查找@throws 异常:PHPDoc 期望此方法有哪些异常?
- benchmarking - Smalltalk 中同一语句中分配和比较的效率
- elasticsearch - Elasticasearch 脚本中无法识别日期时区 ID“美国”
- android - java.lang.OutOfMemoryError:无法分配 2359308 字节分配,224532 可用字节和 219KB 直到 OOM