• 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 style={{'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={{ 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>
        )
      }
    }
  • 相关阅读:
    显示器的分类和主要性能指标
    关闭Win 10 自动更新功能
    MySQL下载安装教程
    经济学十大原理
    西方经济学概述(经济学原理 1 )
    工作表基本操作
    输入和编辑工作表
    因特网概述
    摩尔定律(Moore's Law)
    C 语言编程机制
  • 原文地址:https://www.cnblogs.com/s-z-y/p/6519571.html
Copyright © 2020-2023  润新知