简体   繁体   中英

React rendering a component triggers the onClick event?

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

When this component is rendered, the console.log call is executed without clicking any of the buttons.

I just want to call a method when a button is clicked, nothing really complicated.

Why is that?

It looks like you are trying to use addEmailButton as a closure for the customerId , but it doesn't help because it's the handler that needs the customerId argument, not the rendering of the button.

All you need is to bind the click event with the customerId argument:

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

Or, using ES6 you can use arrow functions instead of self and bind :

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

You should pass to onClick reference to function

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

or if you don't use ES2015 arrow function

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

in your example you are passing to onClick undefined , because console.log() returns undefined , but not reference to function., {} in JSX context means that you can pass to it JS code which you want to execute.

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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