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

Antd Table含Switch的可排序列:点击Switch时如何避免触发排序?

解决Antd Table标题内Switch触发排序的问题

问题根源是事件冒泡:点击Switch时,事件会向上传递到列标题的父容器,而Antd的排序逻辑是监听标题容器的点击事件,所以连带触发了排序。

直接通过阻止事件冒泡就能解决,给Switch的外层容器或者Switch本身添加onClick事件,调用event.stopPropagation()即可:

修改后的代码示例(给外层div加阻止冒泡)

{
  dataIndex: 'owner',
  title:
    <div onClick={(e) => e.stopPropagation()}>
      Owner <Switch
        size="small"
        checkedChildren="Current User"
        unCheckedChildren="All Users"
        onChange={(checked) => {
          setOwnerIsMe(checked)
        }}
      />
    </div>,
  sorter: (a, b) => a.name.localeCompare(b.name),
  ...getColumnSearchProps('owner'),
}

或者直接给Switch加阻止冒泡

{
  dataIndex: 'owner',
  title:
    <div>
      Owner <Switch
        size="small"
        checkedChildren="Current User"
        unCheckedChildren="All Users"
        onClick={(e) => e.stopPropagation()}
        onChange={(checked) => {
          setOwnerIsMe(checked)
        }}
      />
    </div>,
  sorter: (a, b) => a.name.localeCompare(b.name),
  ...getColumnSearchProps('owner'),
}

这样处理后,点击Switch只会触发自身的onChange逻辑,不会再触发列的排序切换。

内容的提问来源于stack exchange,提问作者Anton Petrov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:23:17