最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Close dropdown menu on scroll - Stack Overflow

programmeradmin1浏览0评论

I am currently working on a project using Ant Design and on one page I have a dropdown Menu. 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. 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>

I am currently working on a project using Ant Design and on one page I have a dropdown Menu. 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. 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>
Share Improve this question edited Jan 18, 2019 at 17:16 Thelouras 8801 gold badge11 silver badges30 bronze badges asked Jan 18, 2019 at 17:09 FabianFabian 972 gold badges3 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

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

发布评论

评论列表(0)

  1. 暂无评论