javascript - React 渲染组件会触发 onClick 事件?

标签 javascript function reactjs components mount

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>
    )
  }
});

渲染此组件时,将执行 console.log 调用,而无需单击任何按钮。

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

这是为什么?

最佳答案

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

您所需要做的就是使用 customerId 参数绑定(bind)点击事件:

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>
    )
  })
}

关于javascript - React 渲染组件会触发 onClick 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361850/

相关文章:

javascript - JSON.stringify 和 JSON.parse 不能在 IE9 中工作

c# - 将html有序列表值传递给c#文本框并在sql查询中使用

Javascript 优化...全局变量

javascript - 为什么我的 javascript 函数不抛出错误?

java - Servlet-调用java函数

javascript - 如何动态解构一个巨大的 JSON 对象?

javascript - 将 'onpaste' 属性附加到 JS 函数的元素

JavaScript 检查给定数字中哪一个与其他数字不同

javascript - 如何将 React 元素转换为 dom 元素

javascript - 在 div 之外 react Javascript onclick