如何在 react native (expo) 中获取点击事件(单、双、长)?

gol*_*nus 1 react-native touchableopacity expo

我正在使用 React Native 中的几个点击事件(单、双、长)制作按钮。我已经使用了 Touchable 组件,并且使用时间延迟获得了这些事件。但这不是一个好的解决方案,并且存在一些问题。就是当我双击时,单个事件同时发生。在这种情况下,我必须删除单击事件并获得唯一的双击事件。有没有其他好的解决办法?

abh*_*r22 5

React Native 中的可触摸不透明度没有 onLongpress 或双击支持。

但你可以用TouchableWithoutFeedback,因为它支持onLongPress funtionality。

此外,您只需添加一个自定义代码即可在本机可触摸对象中实现双击。
您可以做的是只保存点击计数并在几秒钟后清除点击计数器,然后在点击两次时触发onPress上的功能 。

在本机反应中双击的示例代码 -

<TouchableWithoutFeedback
    style={{ position: 'absolute', left: 0, padding: 20, backgroundColor:'green' }}
    onPress={() => {
        this.backCount++
        if (this.backCount == 2) {
            clearTimeout(this.backTimer)
            console.warn("Clicked twice")
        } else {
            this.backTimer = setTimeout(() => {
            this.backCount = 0
            }, 3000) #mention here the time for clearing the counter in ms
        }

    }}
>
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

不要忘记在构造函数中初始化 this.backCount = 0