How to stop touch event propagation in React-Native

前端 未结 5 1107
南笙
南笙 2021-02-05 09:12

I have a scrollview with a grid of images when I long press on an image I’d like to stop propagating the mouse events to the scrollview and just monitor the movements. With the

相关标签:
5条回答
  • 2021-02-05 09:54

    I solved this issue by wrap my press event with class method that set inner variable to true, then did the original logic, and after it finished, set again the inner variable to false. Then, you can wrap your container component event handler to check if inner variable set to true or false. for example:

    <TouchableOpacity onPress={this.doSomething1}>
        <TouchableOpacity onPress={this.doSomething2}>
            <Image ... />
        </TouchableOpacity>
    </TouchableOpacity>
    
    doSomething1() {
        this.preventDefault = true;
        doSomeLogic();
        this.preventDefault = false;
    }
    
    doSomething2() {
        if(!this.preventDefault) {
    
        }
    }
    
    0 讨论(0)
  • 2021-02-05 09:54

    In my case, the onPress of the outer touchable was invoked first, even though I pressed the inner touchable.

    What I did, was to use the onPressIn and onPressOut in the inner touchable to determine whether the user pressed the inner or outer touchable - by setting a flag in the component class, on onPressIn and clearing it on onPressOut, and then checking for that flag in the onPress handler of the outer touchable, bailing out if it's set.

    0 讨论(0)
  • 2021-02-05 09:58

    This would be the simplest answer:

    use this on the inner view at the point where you want the propagation to stop

    onTouchEnd={(e) => {
       e.stopPropagation()
    }}
    
    0 讨论(0)
  • 2021-02-05 10:01

    You should take a look at the Gesture Responder's methods: https://facebook.github.io/react-native/docs/gesture-responder-system.html#responder-lifecycle . Actually even simpler way will be to take a look at the PanResponder https://facebook.github.io/react-native/docs/panresponder.html - first see the UIExplorer example to see it in operation: https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/ResponderExample.js . I am not sure though if this will handle the long-press case of yours?

    0 讨论(0)
  • 2021-02-05 10:03

    This might be new since the previous answers, but I find you can just gobble the event using another "touchable":

    <TouchableOpacity onPress={this.onPressOuter}>
        <TouchableOpacity activeOpacity={1}>
            <Text>Content</Text>
        </TouchableOpacity>
    </TouchableOpacity>
    

    In this example, touching the text does not trigger onPressOuter

    0 讨论(0)
提交回复
热议问题