React阻止事件冒泡的正确打开方式

需求:点击导航list按钮出现侧弹框,点击空白处弹框消失

问题:绑定空白处的点击事件到document上,但是非空白处的点击也会触发这个点击事件,在react中如何阻止事件冒泡?

解决方法:e.stopPropagation()并不奏效,react有专属的阻止事件冒泡方法,e.nativeEvent.stopImmediatePropagation()

示例:

/**
 * Created by sunzhuoyi on 17/3/6.
 */
import React from 'react';
import {connect} from 'react-redux';
import {autobind} from 'core-decorators';
import {pushState} from 'redux-router';
import Store from '@comynli/store';
import {Menu, Icon, Row, Col, Dropdown, Button, Affix} from 'antd';

@connect(state => ({}),{pushState})

export default class Common extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      current:'index',
      barDisplay:true
    }
  }

  componentDidMount(){
    document.onclick=this.handleBarDisplayShow;
  }

  @autobind
  handleClick(e) {
    this.setState({
      current: e.key,
    });
  }

  @autobind
  handleInLineClick(e) {
    this.setState({
      current: e.key,
    });
  }

  @autobind
  handleBarDisplay(e){
    e.nativeEvent.stopImmediatePropagation();
    this.setState({barDisplay:false})
  }

  @autobind
  handleBarDisplayShow(){
    e.nativeEvent.stopImmediatePropagation();
    this.setState({barDisplay:true})
  }

  render() {
  const SubMenu = Menu.SubMenu;
  const MenuItemGroup = Menu.ItemGroup;
    return(
      <div 100%'}}>
        <Affix>
          <Menu onClick={this.handleClick}
                mode="horizontal"
                60px',paddingLeft:'20px'}}
          >
            {
              this.state.barDisplay === true ? <Menu.Item key="bars" >
                <Icon type="bars" onClick={e => this.handleBarDisplay(e)}/>
              </Menu.Item> : <span></span>
            }
            <Menu.Item key="Poseidon">
              <a href="/"><b>Poseidon</b></a>
            </Menu.Item>
          </Menu>
        </Affix>
        {
          this.state.barDisplay === false ?
            <Menu onClick={this.handleInLineClick}
                  20px', height: '1500px'}}
                  mode="inline"
            >
               <Menu.Item key="Project">
              <a href="/">Project</a>
            </Menu.Item>
            <Menu.Item key="ProjectTwo">
              <a href="/">Project</a>
            </Menu> : <span></span>
        }
       
      </div>
    )
  }
}