当触摸拖动而不是按下时,如何取消 TouchableOpacity 响应器?

Sin*_*kka 5 react-native

我正在尝试实现我自己的反应本机滑动器组件,但是当在 Animated.View 中添加 TouchableOpacity 时,滑动器立即停止工作。我认为 Touchable 将成为响应者,而我自己的 panResponder 将无法工作。(可以看到按压的不透明度)

问题是我希望可触摸的工作,但如果对屏幕的触摸不是一次点击而是拖动,那么我希望滑动器工作。(当将scrollView与Touchables一起使用时,此行为有效)

这里:开始滚动时使 TouchableOpacity 不突出显示元素 [React Native] 据说:“滚动手势应该取消 TouchableOpacity 触摸响应器” 但这是如何完成的呢?

出于测试目的,我尝试使用以下命令捕获 Animated.View 的响应者:

onStartShouldSetResponderCapture: () => true,
Run Code Online (Sandbox Code Playgroud)

但它似乎没有任何效果(我原以为滑动会起作用,但可触摸则不起作用)。

以下是示例代码(如果将 TouchableOpacity 更改为“查看滑动是否正常”):

import React, { Component } from 'react';
import { View, Animated, PanResponder, Dimensions, TouchableOpacity, Text } from 'react-native';

class App extends Component {

  componentWillMount() {
    const position = new Animated.ValueXY();
    const panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderMove: (event, gesture) => {
        position.setValue({ x: gesture.dx, y: 0 })
      },
      onPanResponderRelease: (event, gesture) => {
          Animated.spring(this.state.position, {
                toValue: { x: 0, y: 0 }
              }).start();
      }
    });
    this.state = { panResponder, position };
  }

  render() {
    return (
          <Animated.View style={[this.state.position.getLayout(), styles.viewStyle]} {...this.state.panResponder.panHandlers}>
              <TouchableOpacity style={styles.touchableStyle}>
                     <Text>Swipe not working</Text>
              </TouchableOpacity>
          </Animated.View>
    );
  }
}

const styles = {
  viewStyle: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    width: Dimensions.get('window').width
  },
  touchableStyle: {
    backgroundColor: '#ddd',
    height: 100,
    borderWidth: 5,
    borderColor: '#000',
    justifyContent: 'center',
    alignItems: 'center'
  }
};

export default App;
Run Code Online (Sandbox Code Playgroud)

如果您有解决方案,请帮助我。我已经尝试让它发挥作用有一段时间了。

Sin*_*kka 1

它设法解决了这个问题:

onStartShouldSetPanResponder: () => true
Run Code Online (Sandbox Code Playgroud)

必须替换为:

onMoveShouldSetPanResponder: () => true
Run Code Online (Sandbox Code Playgroud)

不透明度高亮仍然存在同样的问题,但这并不是什么大问题。 使 TouchableOpacity 在开始滚动时不突出显示元素 [React Native]

  • 该解决方案不适用于 Android 7.0 设备(荣耀 8),触摸按键在 90% 的情况下都会失败。让它工作的解决方法是这样的: `onMoveShouldSetPanResponder: (event,gesture) =&gt; { return Math.abs(gesture.dx) &gt; 5 || Math.abs(gesture.dy) &gt; 5; }` 成立[此处](https://github.com/facebook/react-native/issues/3082) (2认同)