我正在尝试创建一些简单的出生日期下拉菜单,并希望在下拉列表中显示滚动条,并显示固定数量的项目。我怎样才能用 react-bootstrap 做到这一点?我目前的下拉列表离开屏幕并在整个页面上触发滚动条。
这是我的代码:
<FormGroup>
<Col componentClass={ControlLabel} sm={3}>
Birth Date
</Col>
<Col sm={9}>
<DropdownButton title="Month" id="birth-month">
{createMonthSelectItems()}
</DropdownButton>
<DropdownButton title="Day" id="birth-day">
{createDayOfMonthSelectItems()}
</DropdownButton>
<DropdownButton title="Year" id="birth-year">
{createYearSelectItems()}
</DropdownButton>
</Col>
</FormGroup>
另外,请告知这是否是个好主意。我需要这个 UI 在移动设备和桌面上都能很好地工作。
您可以通过为“.dropdown-menu”元素应用固定高度并设置“overflow-y: scroll;”来创建可滚动的下拉列表
反应代码:
import React, { Component } from 'react'
import { DropdownButton, MenuItem } from 'react-bootstrap'
import './QuantityInput.css'
export default class QuantityInput extends Component {
render() {
return (
<DropdownButton
bsStyle="default"
bsSize="small"
style={{ maxHeight: "28px" }}
title={"Qty"}
key={1}
id="dropdown-size-small"
>
<MenuItem eventKey="1">Action</MenuItem>
<MenuItem eventKey="2">Another action</MenuItem>
<MenuItem eventKey="3" active>
Active Item
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">Separated link</MenuItem>
</DropdownButton>
)
}
}
QuantityInput.css
.dropdown-menu {
height: 70px;
overflow-y: scroll;
}
这是一个可能的解决方案,它将根据视口高度动态缩放元素的最大高度:
import React, { Component } from 'react'
import { Button, Dropdown, MenuItem } from 'react-bootstrap'
export default class CustomDropdown extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
toggle = () => {
this.setState({ open: !this.state.open });
}
onToggle = (isOpen, e, source) => {
//This closes the menu on toggling the dropdown or hitting esc.
if (source.source === 'click' || source.source === 'rootClose') {
this.toggle();
}
}
render(){
<div ref={(ref) => this.myRef = ref} className='CustomDropdown'>
<Dropdown open={this.state.open}
onToggle={this.onToggle}
id={'Dropdown'}
>
<Button onClick={this.toggle}
>{this.props.myTitle ? this.props.myTitle : 'Click Me'}</Button>
<Dropdown.Toggle style={{ textAlign: right, paddingBottom: 5 }} />
<Dropdown.Menu style={{overflowY: 'scroll', maxHeight: (window.innerHeight - (this.myRef ? (this.myRef.getBoundingClientRect().top + this.myRef.getBoundingClientRect().height + 100) : 200))}}>
... add menu items here
</Dropdown.Menu>
</Dropdown>
</div>
}
}
将此样式用于可滚动的 DropdownButton
ul.dropdown-menu {
max-height: 500px;
overflow-y: scroll;
}
这会将滚动条设置为 only 在需要时出现并且最大高度相对于视口的高度
.dropdown-menu {
max-height: *percentage of viewport height*vh;
overflow-y: auto;
}