Hii all,这是我的第一个问题,我得到了这个TypeError,但没有强调为什么......请协助 . 未捕获的TypeError:无法读取未定义的属性“Clicked”
class TableComp extends Component{
constructor(props){
super(props)
this.state={
id:"",
name:"",
percentage:"",
status:""
}
}
Clicked(data){
this.setState({
id:data.id,
name:data.name,
percentage:data.percentage,
status:data.status
});
}
PrintTable(){
return (Data.tasks.map(function(data,key){
return(
<tr key={key} onClick={() => this.Clicked(data)}>
<td>{data.id}</td>
<td>{data.name}</td>
<td>{data.percentage}</td>
<td>{data.status}</td>
</tr>
)}));
}
render(){
return(
<Table striped bordered condensed hover>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Percentage</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.PrintTable()}
</tbody>
</Table>
)
}
}
我尝试使用.bind的常规方法,但同样的问题......
3 回答
你应该如你所提到的那样在构造函数中绑定函数 .
问题是你在另一个函数的函数内使用
this
. 在这种情况下,this
不会引用该类 . 要修复此传递箭头函数到您的 Map () . 通过这个你避免这个问题 .你可以阅读更多关于这个here
你应该将你的功能绑定到组件,将你的ctor更改为:
here是完整的解释为什么以及为什么要绑定你的函数:
应该:
即你需要绑定你的函数来调用它们
this.function()
. 请注意,使用函数名称(如functionName()
,而不是FunctionName()
)也是最佳做法 .