【发布时间】:2018-05-05 19:36:23
【问题描述】:
我为我的网络应用程序创建了一个下拉菜单,当我点击一个图标时,我打开了我的下拉菜单。当我单击下拉菜单以外的任何位置时,我想删除下拉菜单。在元素外部单击时,我当前的方法会删除该元素。但是之后单击图标时我无法打开下拉菜单。我该如何解决?
class DropDown extends Component {
constructor(props) {
super(props);
this.myFunction = this.myFunction.bind(this);
this.state = {
openmenu:false
}
};
myFunction(e) {
e.stopPropagation();
this.setState({
openmenu: !this.state.openmenu
})
render() {
window.onclick = function (event) {
if (!event.target.matches('myDropdown')) {
document.getElementById('myDropdown2').remove();
}
}
return (
<div className="dropdown small_font" id="myDropdown" >
<i className="fa fa-cog user_settings_icon" style={{marginTop: '6px'}} onClick={this.myFunction}
aria-hidden="true"></i>
{this.state.openmenu?
<div className="dropdown-content" id="myDropdown2">
<a className="dropdown_item"><i className="fa fa-trash-o margin_right10px" aria-hidden="true"></i>Delete</a>
<a className="dropdown_item"><i className="fa fa-flag-o margin_right10px" aria-hidden="true"></i>Report</a>
</div>:null
}
</div>
);
}
}
第二次点击图标时出现的错误
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
【问题讨论】:
-
您正在删除下拉菜单;你为什么要再次尝试重新打开它;还是它误解了你的话?
-
我听说你没有得到正确的答案?我们能为您做什么?你试过我的方法了吗?
-
@mersocarlin yh 我让它使用 onBlur 函数工作
-
@CraZyDroid 标记正确答案或更新您的问题
标签: javascript jquery reactjs dom