需求:點擊導航list按鈕出現側彈框,點擊空白處彈框消失react
問題:綁定空白處的點擊事件到document上,可是非空白處的點擊也會觸發這個點擊事件,在react中如何阻止事件冒泡?redux
解決方法:e.stopPropagation()並不奏效,react有專屬的阻止事件冒泡方法,e.nativeEvent.stopImmediatePropagation()antd
示例:this
/** * 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 style={{width:'100%'}}> <Affix> <Menu onClick={this.handleClick} mode="horizontal" style={{lineHeight:'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} style={{width: 240, paddingLeft: '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> ) } }