【问题标题】:How to cancel TouchableOpacity responder when touch is dragging instead of pressing?触摸拖动而不是按下时如何取消TouchableOpacity响应器?
【发布时间】:2018-02-22 08:13:28
【问题描述】:

我正在尝试实现我自己的 react-native swiper 组件,但是当在 Animated.View 中添加 TouchableOpacity 时,swiper 立即停止工作。我认为 Touchable 将成为响应者,而我自己的 panResponder 将不起作用。 (可以看到按压的不透明度)

问题是我想让触摸屏工作,但如果触摸屏幕不是一键而是拖动,那么我希望滑动器工作。 (此行为在使用带有 Touchables 的 scrollView 时有效)

这里:Make TouchableOpacity not highlight element when starting to scroll [React Native] 据说:“滚动手势应该取消 TouchableOpacity 触摸响应”但是这是怎么做到的呢?

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

onStartShouldSetResponderCapture: () => true,

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

这是示例代码(如果您将 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;

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

【问题讨论】:

    标签: react-native


    【解决方案1】:

    它设法解决了问题:

    onStartShouldSetPanResponder: () => true
    

    必须替换为:

    onMoveShouldSetPanResponder: () => true
    

    不透明度高亮仍然存在同样的问题,但这不是什么大问题。 Make TouchableOpacity not highlight element when starting to scroll [React Native]

    【讨论】:

    • 此解决方案不适用于 Android 7.0 设备(荣耀 8),Touchable 按压在 90% 的时间都失败。让它工作的解决方法是:onMoveShouldSetPanResponder: (event, gesture) =&gt; { return Math.abs(gesture.dx) &gt; 5 || Math.abs(gesture.dy) &gt; 5; }成立here
    猜你喜欢
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多