我试图点击即可使用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>
);
}
});
这不起作用。然后我尝试在表格中添加一个按钮:
<button className="btn" onClick={this.handleClick}>Full Detail</button>
那也行不通。我在我的应用程序中有其他onClick
工作,但如何使用表格进行此工作?
答案 0 :(得分:29)
您的问题是创建表行的用户函数未绑定到您的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);
});
如果您希望它适用于所有浏览器,请使用Underscore的 bind 。
答案 1 :(得分:4)
我有新的反应。这个怎么样?你只需将它包装在另一个函数中,然后该函数保存闭包范围并正确调用它。
不知道这是不良做法还是性能差异,但似乎有效......
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);
});
答案 2 :(得分:0)
绑定将创建一个新对象。因此,如果您将功能绑定到N个员工,则将无法有效地创建N个新功能。一种更优雅的方法是将函数绑定一次,然后将引用传递给每一行。您的原始代码非常接近。这就是我的建议:
handleClick = e => {
const user = this.state.users.find(u => u.uuid == e.target.dataset.uui)
console.log("clicked");
},
render() {
return(
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Full Detail</th>
</tr>
</thead>
<tbody>
{this.state.users.map(user =>
(
<tr data-uuid={user.uuid} onClick={this.handleClick}>
<td>{user.name}</td>
<td>{user.age}</td>
<td>{user.details || ''}</td>
</tr>
)
)}
</tbody>
</table>
</div>
);
}
});