Antd Select 默认的下拉选项会因为滚动鼠标滚轮而让整个页面滚动,而不是让下拉选项列表滚动。可以通过设置 Select 组件的属性来解决这个问题。
示例代码:
import React from 'react';
import { Select } from 'antd';
const { Option } = Select;
function handleChange(value) {
console.log(`selected ${value}`);
}
function handleMouseEnter(e) {
if (e.target.tagName === 'DIV' && e.target.className.includes('ant-select-dropdown')) {
e.target.getElementsByClassName('ant-select-item')[0].focus();
}
}
function App() {
return (
);
}
export default App;
解决方法为设置 dropdownMatchSelectWidth
为 false
,并在 dropdownMenuStyle
中设置 maxHeight
和 overflow
来限制下拉选项的高度和滚动条出现。同时需要在 Select 组件上绑定 onMouseEnter
事件,并在事件处理函数中判断鼠标进入的元素是否为下拉选项框,如果是则自动为第一个下拉选项设置焦点以防止页面滚动。
上一篇:AntdSelect的值出现类型string[]无法分配给类型string的问题
下一篇:AntdSelect控制台报错:“children应该是Select.Option或Select.OptGroup而不是Option