react中 点击当前组件以外的地方,当前组件隐藏的实现方案:
方案一:
componentDidMount(){
let self = this;
//方法调用
this._onBlurHandler(self)
}
_onBlurHandler(self){
document.body.addEventListener('click', function(e){
//针对不同浏览器的解决方案
function matchesSelector(element, selector){
if(element.matches){
return element.matches(selector);
} else if(element.matchesSelector){
return element.matchesSelector(selector);
} else if(element.webkitMatchesSelector){
return element.webkitMatchesSelector(selector);
} else if(element.msMatchesSelector){
return element.msMatchesSelector(selector);
} else if(element.mozMatchesSelector){
return element.mozMatchesSelector(selector);
} else if(element.oMatchesSelector){
return element.oMatchesSelector(selector);
}
}
//匹配当前组件内的所有元素
if(matchesSelector(e.target,'.citySelectWrap *')){
return;
}
self.setState({
isShowPop:'hide'
})
}, false);
}
方案二:
_onBlurHandler(self) {
document.body.addEventListener( 'click', function(e) {
var cDom = document.querySelector(".repeatSelect");
var tDom = e.target;
if (cDom == tDom || cDom.contains(tDom)) {
} else {
self.setState({ isShow: 'hide' });
}
}, false );
}