Click to react determine whether the location is within the components within the assembly to achieve click an external trigger event

1. Import

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

 

3. Binding monitor events
//监听外部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
            });
        }  
      }

 

Guess you like

Origin www.cnblogs.com/ives/p/11291769.html