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

如何在TypeScript React中为下拉选项绑定不同onClick事件?

React TypeScript下拉菜单选项绑定点击事件失效的解决方案

问题背景

现有Dropdown组件已定义IDropdownOptions接口,包含可选的action回调属性,但在Navbar中为Logout选项绑定handleLogout函数时,错误使用了actions: {handleLogout}的写法,导致自定义点击事件无法触发。

正确实现方式

1. 修正选项的事件属性赋值

在Navbar的optionsDropdown数组中,给Logout选项直接赋值action属性为handleLogout函数,而非错误的actions:

const optionsDropdown: IDropdownOptions[] = [
  {
    id: 1,
    title: 'Chat',
    href: '/',
    typeIcon: 'User',
  },
  {
    id: 2,
    title: 'Notifications',
    href: '/',
    typeIcon: 'User',
  },
  {
    id: 3,
    title: 'Settings',
    href: '/',
    typeIcon: 'User',
  },
  {
    id: 4,
    title: 'Logout',
    href: '/',
    typeIcon: 'User',
    action: handleLogout // 正确绑定自定义事件函数
  },
]

2. 处理a标签的默认跳转干扰

Dropdown组件中每个选项都包含<a>标签,点击会触发默认页面跳转,会覆盖自定义事件逻辑。需要在onClick中阻止默认行为,并执行自定义action:

// Dropdown.tsx中选项渲染部分
{options.map((option) => (
  <li
    key={option.id}
    className='my-1 items-center flex cursor-pointer justify-center'
    onClick={(e) => {
      // 阻止a标签的默认跳转行为
      e.preventDefault();
      // 仅当存在自定义action时执行
      if (option.action) {
        option.action(e);
      } else {
        // 对于不需要自定义事件的选项,手动触发跳转(可选)
        window.location.href = option.href;
      }
    }}
  >
    <a href={option.href}>
      <div className='flex gap-[4px] items-center w-full'>
        <div className='w-[16px] h-[16px] flex items-center justify-center'>
          <Icon className='w-[12px] h-[12px]' type={option.typeIcon} />
        </div>
        <div className='text-[12px] font-normal leading-[18px] w-[116px]'>
          {option.title}
        </div>
      </div>
    </a>
  </li>
))}

3. 额外优化(可选)

如果希望普通选项保持默认跳转行为,仅对Logout这类需要自定义逻辑的选项阻止跳转,可以修改判断逻辑:

onClick={(e) => {
  if (option.action) {
    e.preventDefault();
    option.action(e);
  }
}}

这样没有绑定action的选项会正常触发<a>标签的跳转,绑定了action的选项则执行自定义逻辑。


内容的提问来源于stack exchange,提问作者B A N G A T A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:12:09