javascript - 将值传递给 .bind() 方法

标签 javascript function events arguments bind

如果我调用事件处理函数,我知道我可以使用 .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 - 是我的事件对象,但我也想传递 iduserId

但是当我尝试在我的 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/

相关文章:

javascript - CHIP 8 图形如何在屏幕上呈现?

javascript - 如何使所有子项递归循环?

javascript - Chrome 扩展 : How to modify elements created from an Ajax request in a webpage?

jquery 路径点 : how to bind multiple waypoints on the same object

javascript正则表达式字符串模板提取变量

javascript - 将新函数带入闭包

C++ 结构函数体调用另一个结构函数,同一个模块

PHP:通过引用传递给函数的数组?

javascript - 在EventEmitter上,我如何知道我可以监听的所有事件?

events - 在 NERDtree 上导航时如何更改 vim 工作目录