Lis*_*mUK 0 javascript node.js reactjs
嘿伙计们,我正在尝试渲染一个表中的反应,该表在单击状态时将行设置为选中状态.
单击该行时,我收到如下错误: 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;
Run Code Online (Sandbox Code Playgroud)
用function关键字声明的Javascript函数有自己的this上下文,所以thisinside里面this.props.shows.map( function(show, i)没有引用类.您可以使用箭头语法进行函数声明,这将松散地解析值this.更改
this.props.shows.map(function(show, i)
Run Code Online (Sandbox Code Playgroud)
至
this.props.shows.map((show, i ) => {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |