我试图点击甚至与表格一起工作reactjs.我的第一次尝试是使整行可以点击.这是我的代码:
var UserList = React.createClass({
getInitialState: function() {
return getUsers();
},
handleClick: function(e) {
console.log("clicked");
},
render: function() {
var users = this.state.users.map(function(user) {
return (
<tr onClick={this.handleClick}>
<td>{user.name}</td>
<td>{user.age}</td>
<td></td>
</tr>
);
});
return(
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Full Detail</th>
</tr>
</thead>
<tbody>
{users}
</tbody>
</table>
</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
这没用.然后我尝试在表格中添加一个按钮:
<button className="btn" onClick={this.handleClick}>Full Detail</button>
Run Code Online (Sandbox Code Playgroud)
这也行不通.我有其他onClick人在我的应用程序中工作,但我如何使用表格来完成这项工作?
z5h*_*z5h 32
您的问题是创建表行的用户函数未绑定到您的react组件.值this不是你的反应组件,handleClick不会作为属性存在this.
尝试
var users = this.state.users.map(function(user) {
return (
<tr onClick={this.handleClick}>
<td>{user.name}</td>
<td>{user.age}</td>
<td></td>
</tr>
);}.bind(this);
});
Run Code Online (Sandbox Code Playgroud)
或者如果您希望它在所有浏览器上运行,请使用Underscore的绑定.
我是新来的。这个怎么样?您只需将其包装在另一个函数中,然后该函数将保留闭包范围并正确调用它。
不知道这是不好的做法还是性能差异,但似乎可行...
var users = this.state.users.map(function(user) {
return (
<tr onClick={()=>this.handleClick(user)}>
<td>{user.name}</td>
<td>{user.age}</td>
<td></td>
</tr>
);}.bind(this);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28843 次 |
| 最近记录: |