【发布时间】:2020-04-21 08:03:30
【问题描述】:
我有一个具有以下功能的组件:
constructor(MyProps: Readonly<MyProps>){
super(MyProps);
this.state = {suppliers: [], supplierId:0, supplierName:''};
this.addSupplier.bind(this);
}
addSupplier(){
const {supplierId} = this.state;
alert('supplierId = ' + supplierId);
}
<Button onClick={this.addSupplier}>Add</Button>
状态按预期初始化 b/c this.state.supplierId 在加载时在组件的 html 输入中按预期绑定和显示。 html 输入中的 onChange 处理程序也按预期调用 setState 来更新 state.supplierId。但是,当 addSupplier() 按钮被触发时,会出现以下错误:
TypeError: 无法读取未定义的属性 'supplierId'
因此,由于某种原因,状态在此上下文中不可用。知道这是为什么吗?
【问题讨论】:
标签: reactjs typescript