使用javascript/reactjs单击外部时关闭下拉列表
我创建了一个下拉菜单,当用户单击菜单图标时打开菜单。我已经使用react状态完成了这项工作。当用户在菜单元素外单击时,如何关闭下拉菜单 下拉菜单使用javascript/reactjs单击外部时关闭下拉列表,javascript,jquery,html,reactjs,drop-down-menu,Javascript,Jquery,Html,Reactjs,Drop Down Menu,我创建了一个下拉菜单,当用户单击菜单图标时打开菜单。我已经使用react状态完成了这项工作。当用户在菜单元素外单击时,如何关闭下拉菜单 下拉菜单 class DropDown extends Component { constructor(props) { super(props); this.myFunction = this.myFunction.bind(this); this.state = { o
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>
);
}
}
类下拉列表扩展组件{
建造师(道具){
超级(道具);
this.myFunction=this.myFunction.bind(this);
此.state={
openmenu:错误
}
};
我的职能(e){
e、 停止传播();
这是我的国家({
openmenu:!this.state.openmenu
})
}
render(){
返回(
{/**/}
{this.state.openmenu?
{/**/}
删除
报告
不友好
离开小组
:null
}
);
}
}
您可以在图标上添加onBlur()事件,并编写函数关闭菜单
像这样的东西会有用的
this.closeMenu(){
this.setState({
openmenu: false
})
}
<i onBlur={this.closeMenu} />
this.closeMenu(){
这是我的国家({
openmenu:错误
})
}
今天早上你不是问过同样的问题吗?那可能是我的复制品,但我没有得到一个对我有帮助的答案@RajkumarSomasundaram@CraZyDroiD我问你对那个问题的看法。你没有回应;所以我继续。。