将值传递给.bind()方法

时间:2016-10-28 11:09:43

标签: javascript function events arguments bind

如果我正在调用事件处理函数,我知道我可以使用.bind(this)传递绑定的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定义中,它什么都不返回。

我哪里错了?

1 个答案:

答案 0 :(得分:1)

绑定到函数的参数将在绑定函数接收的 之前提供给它。所以你的函数应该在最后用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")
);
&#13;
<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>
&#13;
&#13;
&#13;