简体   繁体   中英

React Bootstrap: Get drop down menu width

In the below code, How do I determine the dimensions of the menu that appears when you click the button? Currently the menu I'm using is extending outside of the Window. I want to get the dimensions of the menu itself so I can adjust the style of the menu to keep it from extending outside the window.

render: function () {
            return<BS.DropdownButton title={this.props.title} style={this.state.buttonStyle}>
                <span ref="ddMenu">{this.props.children}</span>
            </BS.DropdownButton>
        }

I've tried using ref with getDOMNode().getBoundingClientRect() on the ddMenu , but the dimensions and coordinates are always 0. I've tried using this getDOMNode code in the componentDidMount function. But that runs when the button is rendered, not the menu.

The problem is that the menu's dimensions and coordinates don't exist until the button is pushed. Unfortunately I couldn't find a react way of doing this. So I came up with a none react solution.

The solution is to add an onClick to the button. In the function that is called, add window.setTimeout set for 1 millisecond. Reason: The menu doesn't appear right away, setTimeout gives you just enough time to wait for the menu to show up. Then you can run this.refs.ddMenu.getDOMNode().parentNode. If you don't add parentNode, you will only get the elements you added to the menu, not the menu itself. Once you have the menu, you can then run getBoundingClientRect() to get the menu dimensions and coordinates.

render: function () {
            return<bs.DropdownButton title={this.props.title} onClick={this.getMenu}>
                <div ref="ddMenu">{this.props.children}</div>
            </bs.DropdownButton>
        }

getMenu: function(){
  window.setTimeout(function(){
    var dropMen = this.refs.ddMenu.getDOMNode().parentNode;
  }, 1);
}

dropMen will give you the menu. dropmen.getBoundingClientRect() will give you the menu's dimensions and coordinates. Any css styles added to dropMen will then shown on the menu.

解决此问题的一种方法是使用React-Bootstrap文档中提到的drop directionsmenu align更改下拉菜单的方向和对齐方式对我来说有助于防止扩展窗口的下拉菜单。

Add this css to solve this issue:

   .dropdown-menu {
        min-width: auto !important;
    }
    
    #lang-nav-dropdown {
        width: fit-content;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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