为什么我必须绑定onClick函数而不是调用它

为什么我必须绑定onClick函数而不是调用它

本文介绍了在React中,为什么我必须绑定onClick函数而不是调用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在中,他使用带有bind的onClick函数。

In this tutorial he uses an onClick function with bind.

<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card>

当我像这样删除绑定时

<Card onClick={that.deletePerson(person)} name={person.name}></Card>

我收到错误

我知道 bind 确实如此,但为什么需要这里呢? onClick 是不是直接调用函数吗?

I know what bind does, but why is it needed here? Is the onClick not calling the function directly?

(代码在这个JSbin中:)

(code is in this JSbin: https://jsbin.com/gutiwu/1/edit)

推荐答案

他正在使用 bind ,以便 deletePerson 方法获得正确的参数。

He's using the bind so that the deletePerson method gets the correct person argument.

因为组件未获得完整的对象,这允许他识别实际点击了哪个人的卡。

Because the Card component doesn't get a full Person object, this allows him to identify which person's card was actually clicked.

在您的示例中,您删除了绑定 onClick = {that.deletePerson(person)} 实际上正在评估函数 that.deletePerson(person)并将其设置为onClick。 deletePerson 方法更改了组件的状态,这是错误消息所说的内容。 (在渲染过程中无法更改状态)。

In your example, where you removed the bind onClick={that.deletePerson(person)} is actually evaluating the function that.deletePerson(person) and setting that as onClick. The deletePerson method changes the Component's state, which is what the error message is saying. (You can't change state during a render).

更好的解决方案可能是将id传递给Card,并在删除点击时将其传递回app组件。

A better solution might be to pass the id into Card, and pass it back up to the app component on a delete click.

var Card = React.createClass({
  handleClick: function() {
    this.props.onClick(this.props.id)
  }
  render: function () {
      return (
          <div>
              <h2>{this.props.name}</h2>
              <img src={this.props.avatar} alt=""/>
              <div></div>
              <button onClick={this.handleClick}>Delete Me</button>
          </div>
      )
  }
})

var App = React.createClass({

  deletePerson: function (id) {
    //Delete person using id
  },

  render: function () {
    var that = this;
    return (
        <div>
            {this.state.people.map(function (person) {
                return (
                    <Card onClick={that.deletePerson} name={person.name} avatar={person.avatar} id={person.id}></Card>
                )
            }, this)}
          </div>
      )
  }
})

这篇关于在React中,为什么我必须绑定onClick函数而不是调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:02