Toggle dropdown menu in reactjs

旧时模样 提交于 2019-12-05 08:41:30

Your issue is that clicking on the link will also call the body click listener. It means that your state will go from:

  1. Click on link
  2. Click listener on body called
  3. This.state.open set to false
  4. Render called with this.state.open false
  5. Click listener on the link called
  6. This.state.open set to true
  7. Render called with this.state.open true

e.stopPropagation() doesn't work in React. One workaround would be to:

handleBodyClick: function(e)
{
    if (e.target.nodeName !== 'A') {
       this.setState({isOpen: false});
    }
},

Another way (and better way) would be to have the click listener not on body, but on a div, and make it as big as possible (to be as the same size a body basically).

Here is an example with binding a click on a div instead of body: https://jsfiddle.net/jL3yyk98/

handleClose: function() {
  this.setState({isOpen: false});
},

handleGlobalClick: function(event) {
  var _con = this.refs.mC.getDOMNode() // <component ref="mC">
  if (!(_con == event.target) && !_con.contains(event.target)) {
    this.handleClose();
  }
},

componentDidMount: function() {
  document.body.addEventListener('click', this.handleGlobalClick);
},

componentWillUnmount: function() {
  document.body.removeEventListener('click', this.handleGlobalClick);
},

this work on the latest chrome, you can also use the jQuery rewrite the node.contains()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!