如果我调用事件处理函数,我知道我可以使用 .bind(this)
来传递绑定(bind)的 this
值,但如何传递额外的参数到函数调用?
我有这个:
onSubmit={this.handleSubmit.bind(this, todoListLength, userId)}
那么我的函数定义如下:
handleSubmit(e, id, userId) {
console.log(userId) // returns nothing
console.log(id) // returns nothing
}
第一个参数 - e
- 是我的事件对象,但我也想传递 id
和 userId
。
但是当我尝试在我的 handleSubmit
定义中记录该值时,它什么也没有返回。
我哪里出错了?
最佳答案
您绑定(bind)到函数的参数将在绑定(bind)函数接收的参数之前提供给函数。所以你的函数应该在最后声明它的参数 e
:
handleSubmit(id, userId, e) {
console.log(userId);
console.log(id);
}
这是一个示例,使用 onClick
而不是 onSubmit
,因为 Stack Snippets 不喜欢表单:
class MyForm extends React.Component {
handleSubmit(id, userId, e) {
// Note: `id` seems an odd name for the todoListLength argument ;-)
console.log("id = " + id);
console.log("userId = " + userId);
console.log("e.type = " + e.type);
}
render() {
let {todoListLength, userId} = this.props;
return (
<input type="button" value="Click Me" onClick={this.handleSubmit.bind(this, todoListLength, userId)} />
);
}
}
ReactDOM.render(
<MyForm todoListLength={10} userId={"tjc"} />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
关于javascript - 将值传递给 .bind() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40303821/