我试图在我的reactjs组件外面触发一个事件。目前我有一个可折叠div(蓝色背景),我想在用户点击它之后关闭它。我有一个方法页面点击它来记录事件,但我找不到要使用的属性:
componentDidMount() {
window.addEventListener('mousedown', this.pageClick, false)
}
pageClick(e) {
console.log('testing=pageClick', e)
}
如何检测我是否在使用collapseclass的组件上,以便我可以更改它的状态?
codepen here
答案 0 :(得分:0)
您可以在document
上收听点击事件 -
document.addEventListener("click", this.closeComponent);
作为示例,您可以像这样定义可折叠组件 -
import React, { Component } from 'react';
export default class CollapsibleComponent extends Component {
constructor(props) {
super(props);
this.state = {
style : {
width : 350
}
};
this.showComponent = this.showComponent.bind(this);
this.closeComponent = this.closeComponent.bind(this);
}
componentDidMount() {
document.addEventListener("click", this.closeComponent);
}
componentWillUnmount() {
document.removeEventListener("click", this.closeComponent);
}
showComponent() {
const style = { width : 350 };
this.setState({ style });
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
document.addEventListener("click", this.closeComponent);
}
closeComponent() {
document.removeEventListener("click", this.closeComponent);
const style = { width : 0 };
this.setState({ style });
}
render() {
return (
<div
id = "myCollapsibleComp"
ref = "ccomp"
style = {this.state.style}
>
<div className = "comp-container">
<a
href = "javascript:void(0)"
className = "closebtn"
onClick = {this.closeComponent}
>
×
</a>
</div>
</div>
);
}
}
答案 1 :(得分:0)
您可以检查所点击元素的类,以了解它是否属于您的可折叠元素
componentDidMount() {
window.addEventListener('mousedown', this.pageClick.bind(this), false)
// ^^^^^^^^^^
// bind your function pageClick to this so you can call setState inside
}
pageClick(e) {
const el = e.target;
if (e.target.classList.contains('blue')) {
this.setState({ open: false });
}
}
但这是一个糟糕的解决方案,因为如果您的可折叠元素中有许多不同的DOM节点e.target
将是鼠标下方的元素,而不是父.collapse
元素。
所以我建议您使用库来检测元素外部的点击:react-onclickoutside完美地完成工作。
您可以使用this fiddle中的react-click-outside
来查看用例的实现。