Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useLongPress如何可以控制子元素的onClick事件 #2325

Open
J-Yaleen opened this issue Sep 15, 2023 · 3 comments
Open

useLongPress如何可以控制子元素的onClick事件 #2325

J-Yaleen opened this issue Sep 15, 2023 · 3 comments
Assignees
Labels
feature New feature or request

Comments

@J-Yaleen
Copy link

J-Yaleen commented Sep 15, 2023

背景

  • 我有个组件,希望可以长按显示菜单
image
  • 使用longPress没有问题
  • 但是longPress触发的时候,组件内的子元素onClick也会同时触发,比如图中的‘1’就是子元素的click事件

需求

  • 有没有办法可以实现,如果是长按事件,则不触发子元素的onClick事件
@hchlq
Copy link
Collaborator

hchlq commented Sep 18, 2023

目前看没有很好的解决方案,建议是控制 longPress 的元素,尽量控制在较小的元素范围内

@xgChange
Copy link

xgChange commented Jan 5, 2024

我的解决方法是:

  1. 在父元素上绑定 onClick
  2. 基于 useLongPress 写一个自定义hook,抛出 clickHandler

如下:

const useXXX = (longPressCb, targetRef) => {
  const status = useRef(false)
  useLongPress(longPressCb, targetRef, {
    onClick() {
      status.current = true
    },
    onLongPressEnd() {
      status.current = false
    }
  })

  const clickHandler = (cb) => {
    return (...rest) => {
      if (status.current) {
        cb(...rest)
      }
    }
  }

  return {
    clickHandler
  }
}
<Parent onClick={clickHandler(() => {
  console.log('你的处理')
})}></Parent>

@crazylxr
Copy link
Collaborator

能解决,可以把 useLongPress 的事件传递方式改为捕获,然后在 useLongPress 监听的元素上的事件 通过 event.stopImmediatePropagation() 阻止捕获 应该能解决。

这个我们支持一下

@crazylxr crazylxr added the feature New feature or request label Feb 27, 2024
@crazylxr crazylxr self-assigned this Feb 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants