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

1.导入

import {findDOMNode} from 'react-dom'
2.绑定ref
refTest"

 

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
            });
        }  
      }

 

转载于:https://www.cnblogs.com/ives/p/11291769.html

你可能感兴趣的:(react判断点击位置是否为组件内,实现点击外部触发组件内事件)