
react 实现点击div外部触发事件
大概思路是,为document绑定一个点击事件,判断事件触发对象(e.target)是否是 or 在指定div内部。
首先需要了解两个知识点:
React ref属性
Node.contains()
利用ref属性获取div节点
constructor(){
this.divElement = null;
}
render() {
return(
<div ref={ node => this.divElement = node}><div/>
)
}document添加点击事件
componentDidMount() {
document.addEventListener('click', this.outDivClickHandler);
}卸载document点击事件
componentWillUnmount() {
document.removeEventListener('click', this.outDivClickHandler);
}利用Node.contains()判断触发对象
outDivClickHandler(e) {
const target = e.target;
// 组件已挂载且事件触发对象不在div内
if( this.divElement && target !== this.menu && !this.divElement.contains(target)) {
//do...
}
}
更多相关技术文章,请访问HTML中文网!
以上就是react怎么实现点击事件的详细内容,更多请关注易知道|edz.cc其它相关文章!













