React JS onClick event handler

前端 未结 11 1134
孤街浪徒
孤街浪徒 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:53

    Why not:

    onItemClick: function (event) {
    
        event.currentTarget.style.backgroundColor = '#ccc';
    
    },
    
    render: function() {
        return (
            
    • Component 1
    ); }

    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 (
            
    • Component 1
    • Component 2
    • Component 3
    ); },

    You'd want to put those

  • s into a loop, and you need to make the li.on and li.off styles set your background-color.

提交回复
热议问题