简体   繁体   English

反应-箭头函数vs bind()和带参数的事件

[英]React - Arrow function vs bind() and event with argument

I'm a newbie in react (even in JS). 我是React的新手(即使在JS中)。 I'm made the following code in my App class: 我在我的App类中编写了以下代码:

nameChangeHandler = (event, personId) => {
//method code
};

render()
{
  <div>
    {this.state.persons.map((person, index) => {
      return <Person
          // nameChangeHandler={(event) => this.nameChangeHandler(event, person.id)}
          nameChangeHandler={this.nameChangeHandler.bind(this, person.id)}
      />
    })}
  </div>
}

I'm passing nameChangeHandler to Person component where I call it in onChange event in input tag ( <input type="text" onChange={props.nameChangeHandler}/> ) 我将nameChangeHandler传递给Person组件,在input标签的onChange事件中将其调用( <input type="text" onChange={props.nameChangeHandler}/>

Application works fine when I pass it in this way: 当我通过这种方式传递应用程序时,它运行良好:
nameChangeHandler={(event) => this.nameChangeHandler(event, person.id)}
but it doesn't when I do it like this: 但是当我这样做时却不是这样:
nameChangeHandler={this.nameChangeHandler.bind(this, person.id)}

It fails with an exception when I'm trying to acces event.target.value in nameChangeHandler method. 当我尝试访问nameChangeHandler方法中的event.target.value时,它失败并发生异常。

How can I pass event and argument to this method using bind() method instead of arrow function? 如何使用bind()方法而不是arrow函数将事件和参数传递给此方法?

I've heard we should always use bind() approach over the arrow function because an arrow function approach could render component many times. 我听说我们应该始终在arrow函数上使用bind()方法,因为arrow函数方法可以多次渲染组件。

Is there any special use cases and differences between bind() and arrows functions? 有没有特殊的用例以及bind()和arrow函数之间的区别?

It's a matter of timing. 这是时间问题。

When you use bind , the arguments map on to the function you are binding in the order you bind them followed by any that are passed to the new function. 当使用bind ,参数将按照绑定它们的顺序映射到您要绑定的函数, 然后再传递给新函数。

When you use an arrow function, you are explicitly passing them in the order you determine. 使用箭头功能时,将按您确定的顺序显式传递它们。

Your function expects event to be the first argument, so when you use an arrow you function you pass event, person.id . 您的函数期望event是第一个参数,因此,当您使用箭头时,函数会传递event, person.id However, when you bind you pass person.id (the first argument) and when the function is called with event you pass that (as the second argument). 但是,在绑定时,您传递person.id (第一个参数),并在通过event调用函数时将其传递(作为第二个参数)。

This means you arguments end up the wrong way around. 这意味着您的论点最终走错了路。

Since you only have person.id when you call bind and you don't get event until later, the only way you can use bind for this is to change the original function so it accepts the arguments in a different order. 由于在调用bind只有一个person.id ,直到以后才获取event ,因此可以使用bind的唯一方法是更改原始函数 ,使其以不同的顺序接受参数。

nameChangeHandler = (personId, event) => {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM