You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为react-select组件的menuList添加onScroll滚动事件处理函数

解决react-select menuList绑定onScroll事件不生效的问题

失效原因

你之前的两种写法失效分别对应两个核心原因:

  • 内层包裹div的写法:真正产生滚动的是components.MenuList自身渲染的带overflow: auto属性的外层容器,你包裹的内层div高度完全由内容撑开,本身不会产生滚动行为,自然无法触发onScroll事件
  • ref直接绑定的写法:react-select没有将menuList的实例直接暴露在Select组件的顶层ref下,所以无法通过current.menuListRef的方式获取到对应DOM元素

正确实现方式

直接将onScroll事件绑定到components.MenuList底层渲染的原生滚动容器上即可,通过修改自定义MenuList组件的innerProps实现,innerProps是react-select专门用于向底层原生DOM传递属性的参数:

import React from 'react';

import Select, { components, MenuListProps } from 'react-select';
import {
  ColourOption,
  colourOptions,
  FlavourOption,
  GroupedOption,
  groupedOptions,
} from './docs/data';

const MenuList = (
  props: MenuListProps<ColourOption | FlavourOption, false, GroupedOption>
) => {
  const handleScroll = () =>{
    console.log('scrolling')
  }
  // 合并原有innerProps,添加滚动事件到原生滚动容器
  const modifiedInnerProps = {
    ...props.innerProps,
    onScroll: handleScroll
  }
  return (
    <components.MenuList {...props} innerProps={modifiedInnerProps}>
      {props.children}
    </components.MenuList>
  );
};

export default () => (
  <Select<ColourOption | FlavourOption, false, GroupedOption>
    defaultValue={colourOptions[1]}
    menuIsOpen={true}
    options={groupedOptions}
    components={{ MenuList }}
  />
);

这个写法无需额外的ref绑定、定时器等hack逻辑,完全符合react-select的自定义组件规范,滚动事件可以稳定触发。


内容的提问来源于stack exchange,提问作者Dan Cancro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:54:04