我创建了一个下拉菜单,当用户点击菜单图标时打开菜单。我用反应状态完成了这个。当用户点击菜单元素外部时,如何关闭下拉菜单?
下拉菜单
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() {
return (
<div className="dropdown small_font" id="myDropdown" onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp}>
{/*<img src={settings} onClick={this.myFunction} className="user_settings_icon"></img>*/}
<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">
{/*<div id="myDropdown" className={this.props.actionDropDownCSS}>*/}
<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>
<a className="dropdown_item"><i className="fa fa-minus-square-o margin_right10px" aria-hidden="true"></i>Unfriend</a>
<a className="dropdown_item"><i className="fa fa-sign-out margin_right10px" aria-hidden="true"></i>Leave group</a>
</div>:null
}
</div>
);
}
}
答案 0 :(得分:0)
您可以在图标上添加onBlur()事件并编写一个关闭菜单的功能
这样的事情会起作用
this.closeMenu(){
this.setState({
openmenu: false
})
}
<i onBlur={this.closeMenu} />