简体   繁体   English

滚动时关闭下拉菜单

[英]Close dropdown menu on scroll

I am currently working on a project using Ant Design and on one page I have a dropdown Menu.我目前正在使用Ant Design进行一个项目,并且在一个页面上我有一个下拉菜单。 When you click on the menu it opens the dropdown but if you scroll down the menu still keeps open.当您单击菜单时,它会打开下拉菜单,但如果您向下滚动,菜单仍会保持打开状态。 I wish to implement that when the user is scrolling down the menu closes.我希望在用户向下滚动菜单关闭时实现。

I tried to implement a handleScroll() function in order to use is with the provided prop onVisibleChange .我试图实现一个handleScroll()函数,以便与提供的道具onVisibleChange However I am not sure what I should add in the function to get it work.但是我不确定我应该在函数中添加什么才能让它工作。

handleScroll = (e) => {
window.addEventListener('scroll', () => {
console.log('scrolling');
 })
}

<Dropdown onVisibleChange={visible => this.handleScroll( 
console.log(visible)) } trigger={['click']} overlay={
  <Menu>
    <Menu.Item key="1"
      onClick={() => this.scrollTo(this.whyRef)}>
      <Icon icon={u1F427} /> <strong>WHY</strong>
      </Menu.Item>
     </Menu>
   }>
 <Dropdown>

You need to add the event listener in the constructor and handle the visibility state of the dropdown yourself.您需要在构造函数中添加事件侦听器并自己处理下拉列表的可见性状态。 Try something like this:尝试这样的事情:

 class Example extends React.Component { constructor(props) { super(props); this.state = { visible: false }; window.addEventListener("scroll", this.closeMenu); } toggleMenu = () => { this.setState({ visible: !this.state.visible }); }; closeMenu = () => { this.setState({ visible: false }); }; render() { return ( <div> <Dropdown overlay={menu} onVisibleChange={this.toggleMenu} visible={this.state.visible} trigger={["click"]} > <a className="ant-dropdown-link" href="#"> Click me <Icon type="down" /> </a> </Dropdown> </div> ); } }

Working example: https://codesandbox.io/s/2ovjzwqz9y工作示例: https : //codesandbox.io/s/2ovjzwqz9y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM