React JS onClick event handler

前端 未结 11 1085
孤街浪徒
孤街浪徒 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(
           <div>
             <ul>
                <li onClick={this.getComponent.bind(this)}>Component 1</li>
             </ul>
           </div>
        );
      }
    }
    
    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() {        
           <div>
             <ul>
             {this.state.data.map(d => {
               return(
                  <li key={d.id} onClick={this.getComponent.bind(this)}>{d.name}</li>
               )}
             )}
             </ul>
           </div>
        );
      }
    }
    
    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(
          <li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
        )}
    )}
    
    0 讨论(0)
  • 2020-11-28 21:39

    Two ways I can think of are

    var TestApp = React.createClass({
        getComponent: function(index) {
            $(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
                'background-color': '#ccc'
            });
        },
        render: function() {
            return (
                <div>
                  <ul>
                    <li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
                    <li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
                    <li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
                  </ul>
                </div>
            );
        }
    });
    React.renderComponent(<TestApp /> , document.getElementById('soln1'));
    

    This is my personal favorite.

    var ListItem = React.createClass({
        getInitialState: function() {
            return {
                isSelected: false
            };
        },
        handleClick: function() {
            this.setState({
                isSelected: true
            })
        },
        render: function() {
            var isSelected = this.state.isSelected;
            var style = {
                'background-color': ''
            };
            if (isSelected) {
                style = {
                    'background-color': '#ccc'
                };
            }
            return (
                <li onClick={this.handleClick} style={style}>{this.props.content}</li>
            );
        }
    });
    
    var TestApp2 = React.createClass({
        getComponent: function(index) {
            $(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
                'background-color': '#ccc'
            });
        },
        render: function() {
            return (
                <div>
                 <ul>
                  <ListItem content="Component 1" />
                  <ListItem content="Component 2" />
                  <ListItem content="Component 3" />
                 </ul>
                </div>
            );
        }
    });
    React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
    

    Here is a DEMO

    I hope this helps.

    0 讨论(0)
  • 2020-11-28 21:42

    Here is how you define a react onClick event handler, which was answering the question title... using es6 syntax

    import React, { Component } from 'react';
    
    export default class Test extends Component {
      handleClick(e) {
        e.preventDefault()
        console.log(e.target)
      }
    
      render() {
        return (
          <a href='#' onClick={e => this.handleClick(e)}>click me</a>
        )
      }
    }
    
    0 讨论(0)
  • 2020-11-28 21:46

    import React from 'react';
    
    class MyComponent extends React.Component {
    
      getComponent(event) {
          event.target.style.backgroundColor = '#ccc';
          
          // or you can write
          //arguments[0].target.style.backgroundColor = '#ccc';
      }
    
      render() {
        return(
           <div>
             <ul>
                <li onClick={this.getComponent.bind(this)}>Component 1</li>
             </ul>
           </div>
        );
      }
    }
    
    export { MyComponent };  // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'
    export default MyComponent;

    0 讨论(0)
  • 2020-11-28 21:47

    You can make use of the React.createClone method. Create your element, than create a clone of it. During the clone's creation, you can inject props. Inject an onClick : method prop like this

    { onClick : () => this.changeColor(originalElement, index) }

    the changeColor method will set the state with the duplicate, allowing you sto set the color in the process.

    render()
      {
        return(
          <ul>
    
            {this.state.items.map((val, ind) => {
              let item = <li key={ind}>{val}</li>;
              let props = { 
                onClick: () => this.Click(item, ind),
                key : ind,
                ind
              }
              let clone = React.cloneElement(item, props, [val]);
              return clone;
            })}
    
          </ul>
        )
      }

    0 讨论(0)
  • 2020-11-28 21:53

    Why not:

    onItemClick: function (event) {
    
        event.currentTarget.style.backgroundColor = '#ccc';
    
    },
    
    render: function() {
        return (
            <div>
                <ul>
                    <li onClick={this.onItemClick}>Component 1</li>
                </ul>
            </div>
        );
    }
    

    And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render:

    onItemClick: function (event) {
    
        this.setState({ selectedItem: event.currentTarget.dataset.id });
        //where 'id' =  whatever suffix you give the data-* li attribute
    },
    
    render: function() {
        return (
            <div>
                <ul>
                    <li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
                    <li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
                    <li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
                </ul>
            </div>
        );
    },
    

    You'd want to put those <li>s into a loop, and you need to make the li.on and li.off styles set your background-color.

    0 讨论(0)
提交回复
热议问题