简体   繁体   中英

React onClick Not Working

I'm trying to create a dropdown menu in React, and I don't understand why the onClick event listener in the return is not working. The menu is loading as expected initially with no dropdown visible, however when I click on the class nothing happens.

var NavLinkContainer = React.createClass({
  getInitialState: function(){
    return {
      listVisible: false
    };
  },
  show: function(){
    this.setState({
      listVisible: true
    });
  },
  hide: function(){
    this.setState({
      listVisible: false
    });
  },
  generateItem: function(item){
    return <NavLink bold={item.bold} key={item.id} url={item.url} text={item.text}/>
  },
  render: function(){
    var items = this.props.items.map(this.generateItem);
    var visible = this.state.listVisible;
    var listClass;
    if (visible){
      listClass = 'navlinkcontainer';
    } else {
      listClass = 'navlinkcontainer hide'
    }
    return (
      <ul className={listClass} onClick={this.show}>
        {items}
      </ul>
    );
  }
});

onClick is working fine, and there is nothing wrong with your show function. You can see in this bin that the function is getting called and the state is updating appropriately: http://jsbin.com/dazonovowi

You probably have a problem with your CSS, so check that first, and then check whether any child components are rendering improperly. A good way to solve your CSS problem: try setting listVisible to true in your getInitialState and design how the component should look fully expanded, then set it back to false when you're ready to test the functionality again.

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