嘿,大家好,我正在尝试在 React 中渲染一个表格,该表格将一行设置为在单击时的状态下选定。
单击该行时,我收到如下错误:Uncaught TypeError: Cannot read property 'setSelected' of undefined
有很多关于此的问题,解决方案似乎是添加行 this.setSelected = this.setSelected.bind(this);
到构造函数,以便该函数实际上是可访问的。
我已经知道要这样做,正如您在下面看到的,我已经做到了,但它仍然给我错误。我完全被难住了。
import React, { Component } from 'react';
class ShowsList extends Component {
constructor(props) {
super(props);
this.state = {selected: {showID: null, i: null}};
this.setSelected = this.setSelected.bind(this);
}
setSelected(event, showID, i) {
this.setState({
selected: {showID, i}
});
console.log(this.state.selected);
}
render() {
return (
<div className="shows-list">
<table className="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Location</th>
<th scope="col">Date</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{this.props.shows.map( function(show, i) {
return (
<tr
key={i}
onClick={(e) => {this.setSelected(e, show._id, i)}}>
<td>{i+1}</td>
<td>{show.eventName}</td>
<td>{show.location}</td>
<td>{show.date}</td>
<td>{show.startTime}</td>
</tr>);
})}
</tbody>
</table>
</div>
);
}
}
export default ShowsList;
使用 function 关键字声明的 JavaScript 函数有自己的 this
上下文,因此 this.props.shows.map( function(show, i)
中的 this
并不引用该类。您可以使用箭头语法进行函数声明,这将宽松地解析 this
的值。更改
this.props.shows.map(function(show, i)
至
this.props.shows.map((show, i ) => {
我是一名优秀的程序员,十分优秀!