【发布时间】:2018-07-24 03:14:17
【问题描述】:
大家好,我正在尝试在 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;
【问题讨论】:
标签: javascript node.js reactjs