在react native中同时按下按钮

3htmauhk  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(69)

我需要能够在我的应用程序中同时按下多个按钮,但我不知道如何实现它。标准的Pressable组件和onPress,onPressIn,onPressOut功能不起作用,因为一次只能按下一个按钮。
我已经看到以前的答案,如“https://stackoverflow.com/questions/42776490/how-do-i-enable-touch-on-multiple-buttons-simultaneously-in-react-native/42779656#42779656“。他们建议我应该使用一个View组件和onTouchStart,onTouchEnd函数,但这些都不起作用,就像许多人在评论中指出的那样。每当我开始按下一个按钮,它就会注册它,但当我试图按下屏幕上的其他任何地方(按下的View组件甚至其他组件之外)时,它会重新注册相同的初始按钮按下。

<View
  onTouchStart={() => console.log(1)}
  style={{ width: 50, height: 50, backgroundColor: 'red' }}
/>
<View
  onTouchStart={() => console.log(2)}
  style={{ width: 50, height: 50, backgroundColor: 'red' }}
/>

字符串
对于这段代码,如果我按下第一个按钮,1将登录到控制台,然后按屏幕上的任何位置,1将再次登录到控制台。
最新消息:我刚刚在iOS上测试了它,它工作得很好,所以这个问题只在Android上出现。当按住视图时,触摸响应区域似乎会扩展到整个屏幕,我找不到一种方法将其限制在视图本身。

lb3vh1jj

lb3vh1jj1#

我最终使用了react-native-gesture-handler中的GestureDetector,并实现了自己的自定义Pressable组件。
请注意,这段代码来自2021年,所以可能对包及其工作方式进行了一些更新。我建议您阅读documentation,但无论如何,这是我所拥有的。

import React, { useState } from 'react';
import { View } from 'react-native';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';

export default function CustomPressable({
  children,
  onBegin,
  onEnd,
  maxDuration = 100000,
}) {
  const [isPressed, setPressed] = useState(false);
  const tapGesture = Gesture.Tap()
    .maxDuration(maxDuration)
    .onBegin(() => {
      setPressed(true);
      onBegin();
    })
    .onEnd(() => {
      setPressed(false);
      onEnd();
    });

  return (
    <GestureDetector gesture={tapGesture}>
      <View style={isPressed && { backgroundColor: 'rgba(255,255,255,0.5)' }}>
        {children}
      </View>
    </GestureDetector>
  );
}

字符串

相关问题