我创建了一个包含React组件的小而简单的脚本:
var React = require('react');
var UsersList = React.createClass({
handleRedirection: function(userName){
window.location = '/user/'+userName;
},
render: function(){
return(
<table>
<tbody>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Day of Birth</th>
<th>Username</th>
<th>Role</th>
<th></th>
</tr>
{this.props.content.map(function(user, i) {
return (
<tr key={i}>
<td>{user.name}</td>
<td>{user.surname}</td>
<td>{user.birthday}</td>
<td>{user.userName}</td>
<td>{user.userRole}</td>
<td><button onClick={this.handleRedirection(user.userName)}>Open</button></td>
</tr>
);
})}
</tbody>
</table>
)
}
})
module.exports = UsersList;
编译时,我确实在浏览器中遇到以下错误:
未捕获的TypeError:this.handleRedirection不是函数
我相信调用函数的方式似乎都是正确的,问题可能出在哪里?
答案 0 :(得分:3)
您需要将this
绑定到函数:
{this.props.content.map(function(user, i) {
return (
<tr key={i}>
<td>{user.name}</td>
<td>{user.surname}</td>
<td>{user.birthday}</td>
<td>{user.userName}</td>
<td>{user.userRole}</td>
<td><button onClick={this.handleRedirection.bind(null, user.userName)}>Open</button></td>
</tr>
);
}.bind(this))}
答案 1 :(得分:1)
您直接调用setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
//Remove any existing WindowListeners
for ( WindowListener wl : this.getWindowListeners())
this.removeWindowListener(wl);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if ("Optional condition") {
JOptionPane.showMessageDialog(null, "You cannot close this window");
}
}
});
并将返回值作为事件处理程序而不是函数传递。
相反,只有在事件被触发后才将调用包装到函数中以调用handleRedirection()
:
handleRedirection()
答案 2 :(得分:1)
我为您准备了这个演示:http://codepen.io/PiotrBerebecki/pen/ZpBwWz
您可以使用onClick={this.handleRedirection.bind(null, user.userName)}
创建新功能,而无需在渲染时调用。此外,user.userName
将作为第一个参数传递。
var UsersList = React.createClass({
handleRedirection: function(userName) {
console.log(userName);
window.location = '/user/' + userName;
},
render: function() {
return (
<table>
<tbody>
<tr>
<th>Name</th>
<th>Surname</th>
<th></th>
</tr>
{this.props.content.map((user, i) => {
return (
<tr key={i}>
<td>{user.name}</td>
<td>{user.surname}</td>
<td><button onClick={this.handleRedirection.bind(null, user.userName)}>Open</button></td>
</tr>
);
})}
</tbody>
</table>
)
}
});