[英]Close react button dropdown menu on clicking or hovering outside of menu area
[英]React - Close dropdown menu when clicking on the window
我有一個可以正確打開的下拉菜單,您可以單擊並將其滾動到右側部分。 我還實現了再次單擊該按鈕時下拉列表將關閉的功能。
我現在正在嘗試在菜單外部單擊以實現下拉菜單。
目前,我找到的最佳解決方案是在窗口上添加click事件監聽器。
這會導致出現問題,即您單擊以打開下拉列表時,它將直接關閉它。 這就是為什么我添加了新狀態以便可以添加條件的原因,但這是行不通的。
有人可以描述一下React做到這一點的最佳方法是什么?
提前致謝
class Explore extends Component {
constructor(props){
super(props)
this.state = {
visible: false,
hide: false
}
this.whyRef = React.createRef()
this.overviewRef = React.createRef()
window.addEventListener('scroll', this.closeMenu);
// if(this.state.hide === true) window.addEventListener('click', this.closeMenu);
}
toggleMenu = () => {
if(!this.state.visible){
this.setState({ visible: true, hide: true });
} else {
this.setState({ visible: false, hide: false});
}
}
closeMenu = () => {
this.setState({ visible: false });
}
scrollTo = (ref) => {
window.scrollBy({
top:ReactDOM.findDOMNode(ref.current).getBoundingClientRect().top - 200,
behavior: "smooth" // Optional, adds animation
})
}
render() {
const { visible, hide } = this.state
return (
<Dropdown
visible={visible}
onClick={this.toggleMenu}
trigger={['click']} overlay={
<Menu>
<Menu.Item key="1"
onClick={() => this.scrollTo(this.whyRef)}>
<Icon icon={u1F427} /> <strong>WHY</strong>
</Menu.Item>
<Menu.Item key="2" onClick={() => this.scrollTo(this.overviewRef)}>
<Icon icon={u1F30D} /> 30,000 Feet
</Menu.Item>
</Menu>
}>
<Button style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}
size="small">
<strong className="text-grey clickable">
<Icon icon={infoCircle} size={14}/> SECTIONS
</strong>
</Button>
</Dropdown>
}
您可以嘗試用onFocus
替換onClick
來打開下拉菜單,並添加onBlur
來關閉下拉菜單。 單擊該元素時將觸發onFocus
,而“取消聚焦”(在外部單擊)時將觸發onBlur
。 還需要tabIndex
屬性/ prop,焦點/模糊才能在非輸入類型元素上工作。 而且我認為您誤會了state
。 用visible={this.state.visible}
替換visible={visible}
,並在您注釋掉eventListener
刪除了trigger={['click']}
。
代碼看起來像這樣:
toggleMenu = () => {
this.setState({ visible: !this.state.visible });
}
....
....
<Dropdown
visible={this.state.visible}
onFocus={this.toggleMenu}
onBlur={this.toggleMenu}
tabIndex="0"
overlay={
....
....
</Dropdown>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.