React 渲染一个组件会触发 onClick 事件

React rendering a component triggers the onClick event?

本文关键字:组件 事件 onClick 一个 React      更新时间:2023-11-26
var CustomerTable = React.createClass({    
  addEmailButton: function(customerId) {
    console.log(customerId);
    return (
      <button onClick={console.log("clicked", customerId)}>X</button>
    )
  },
  render: function() {
    var self = this;
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {
              this.state.customers.map(function(customer, i) {
                return (
                  <tr key={i}>
                    <td>{self.addEmailButton(customer['id'])}</td>
                  </tr>
                )
              })
            }
          </tbody>
        </table>
      </div>
    )
  }
});

呈现此组件时,无需单击任何按钮即可执行控制台.log调用。

我只想在单击按钮时调用一个方法,没有什么真正复杂的。

为什么?

看起来您正在尝试使用 addEmailButton 作为customerId的闭包,但这无济于事,因为需要 customerId 参数的是处理程序,而不是按钮的呈现。

您所需要的只是使用 customerId 参数bind click 事件:

var CustomerTable = React.createClass({    
  handleClick: function(customerId, event) {
    console.log("clicked", customerId);
  },
  render: function() {
    var self = this;
    return (
      <...>
        {
          this.state.customers.map(function(customer, i) {
            return (
              <tr key={i}>
                <td>
                  <button onClick={self.handleClick.bind(self, customer['id'])}>X</button>
                </td>
              </tr>
            )
          })
        }
      <...>
    )
  }
});

或者,使用 ES6,您可以使用箭头函数代替 selfbind

{
  this.state.customers.map((customer, i) => {
    return (
      <tr key={i}>
        <td>
          <button onClick={(e) => this.handleClick(customer['id'])}>X</button>
        </td>
      </tr>
    )
  })
}

你应该传递给函数onClick引用

<button onClick={() => console.log("clicked", customerId)}>X</button>

或者如果您不使用箭头功能 ES2015

<button onClick={function () { console.log("clicked", customerId) } }>X</button>

在您的示例中,您正在传递给onClick undefined,因为console.log()返回undefined,但不引用函数,{} JSX上下文中意味着您可以将要执行的 JS 代码传递给它。

Example