React JS onClick event handler

前端 未结 11 1124
孤街浪徒
孤街浪徒 2020-11-28 21:35

I have

var TestApp = React.createClass({
      getComponent: function(){
          console.log(this.props);
      },
      render: function(){
        retur         


        
11条回答
  •  离开以前
    2020-11-28 21:35

    If you're using ES6, here's some simple example code:

    import React from 'wherever_react_is';
    
    class TestApp extends React.Component {
    
      getComponent(event) {
          console.log('li item clicked!');
          event.currentTarget.style.backgroundColor = '#ccc';
      }
    
      render() {
        return(
           
    • Component 1
    ); } } export default TestApp;

    In ES6 class bodies, functions no longer require the 'function' keyword and they don't need to be separated by commas. You can also use the => syntax as well if you wish.

    Here's an example with dynamically created elements:

    import React from 'wherever_react_is';
    
    class TestApp extends React.Component {
    
    constructor(props) {
      super(props);
    
      this.state = {
        data: [
          {name: 'Name 1', id: 123},
          {name: 'Name 2', id: 456}
        ]
      }
    }
    
      getComponent(event) {
          console.log('li item clicked!');
          event.currentTarget.style.backgroundColor = '#ccc';
      }
    
      render() {        
           
      {this.state.data.map(d => { return(
    • {d.name}
    • )} )}
    ); } } export default TestApp;

    Note that each dynamically created element should have a unique reference 'key'.

    Furthermore, if you would like to pass the actual data object (rather than the event) into your onClick function, you will need to pass that into your bind. For example:

    New onClick function:

    getComponent(object) {
        console.log(object.name);
    }
    

    Passing in the data object:

    {this.state.data.map(d => {
        return(
          
  • {d.name}
  • )} )}

提交回复
热议问题