react判断点击位置是否为组件内,实现点击外部触发组件内事件

1.导入

import {findDOMNode} from 'react-dom'
2.绑定ref
<div  ref="refTest"
</div>

 

3.绑定监听事件
//监听外部click
    componentDidMount() {
        document.addEventListener('mousedown', (e)=>this.handleClickOutside(e), false);
      }
      componentWillUnmount() {
        document.removeEventListener('mousedown', (e)=>this.handleClickOutside(e), false);
      }
      handleClickOutside(e) {
        const target = e.target;
        console.log(target);
        console.log(this);
        // 组件已挂载且事件触发对象不在div内
        let result=findDOMNode(this.refs.refTest).contains(e.target);
        if( !result) {
            console.log("ssscs");
            this.setState({
                ulShow:false
            });
        }  
      }

 

posted @ 2019-08-02 23:50 Hey,Coder! 阅读(...) 评论(...) 编辑 收藏