我为我的网络应用程序创建了一个下拉菜单,当点击一个图标时,我打开了我的下拉菜单。当我单击下拉菜单以外的任何地方时,我想删除下拉菜单。我当前的方法是在元素外部单击时删除元素。但是之后单击图标时我无法打开下拉菜单。我该如何解决?
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.