当Button disabled为true时,mouseleave事件不触发-React/Antd

在使用Antd 中 Tooltip 都有遇到,触发元素有可能是被禁用的按钮。

最开始的代码:

<Tooltip title="prompt text">
    <Button
        type="link"
        disabled={somecondition}
        onmouseenter={()=>{console.log('enter')}}
        onmouseleave={()=>{console.log('leave')}}
     >
       按钮
    </Button>
</Tooltip>

逻辑就是通过监听按钮的移入和移出事件来模拟hover,控制Tooltip的显隐,当button是disabled状态是true,只触发mouseenter事件,而不触发mouseleave事件。

原因可能是被禁用的表单元素不会触发其他的事件。

解决办法:

  1. 在按钮外面包一层div,将事件添加到这个div上。这时因为还存在另外一个问题,子元素是disabled,移出时也不会触发,需要给div加一些padding来撑开距离。但是实际的使用过程中发现如果快速移入移出有时会失效。
  2. 模拟元素的禁用样式,不禁用元素,这样就不会影响事件了。

解决代码:

<Tooltip title="prompt text">
  <span
      className={classnames({
      [demo]: somecondition,
  })}>
    <Button
        type="link"
        disabled={somecondition}
     >
       按钮
    </Button>
  </span>
</Tooltip>

样式:

.demo {
  position: relative;
  display: inline-block;

  &::after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 10;
    cursor: not-allowed;
  }
}
posted @ 2022-10-28 16:36  我的诗和远方  阅读(383)  评论(0编辑  收藏  举报