React Native: View onPress does not work

2020-05-12 04:47发布

问题:

I'm facing a weird problem. In my react native app, if I set onPress event to View it is not triggered but if I set the same to Text inside View, it fires. What am I missing here?

<View style={{backgroundColor: "red", padding: 20}}>
  <Text onPress={()=> {
    console.log('works');
    }
  }>X</Text>
</View>


<View style={{backgroundColor: "red", padding: 20}} onPress={()=> {
    console.log('does not work');
    }
  }>
  <Text>X</Text>
</View>

Why is this so? Is this an issue with React Native? I'm using version 0.43

回答1:

You can use TouchableOpacity for onPress event. View doesn't provide onPress prop.

<TouchableOpacity style={{backgroundColor: "red", padding: 20}} onPress={()=> {
    console.log('does not work');
    }
  }>
  <Text>X</Text>
</TouchableOpacity>


回答2:

You can wrap the view with a TouchableWithoutFeedback and then use onPress and friends like usual. Also you can still block pointerEvents by setting the attribute on on the child view, it even blocks pointer events on the parent TouchableWithoutFeedback, its interesting, this was my need on Android, I didn't test on iOS:

https://facebook.github.io/react-native/docs/touchablewithoutfeedback.html

<TouchableWithoutFeedback onPressIn={this.closeDrawer}>
    <Animated.View style={[styles.drawerBackground, styleBackground]} pointerEvents={isOpen ? undefined : 'none'} />
</TouchableWithoutFeedback>


回答3:

You can use TouchableOpacity, TouchableHighlight, TouchableNativeFeedback, to achieve this. View component doesn't provide onPress as props. So you use these instead of that.

<TouchableNativeFeedback
        onPress={this._onPressButton}
</TouchableNativeFeedback>

OR

<TouchableHighlight onPress={this._onPressButton}>
</TouchableHighlight>

OR

<TouchableOpacity onPress={this._onPressButton}>
</TouchableOpacity>



回答4:

Alternatively you can also provide onStartShouldSetResponder to your view, like so:

<View onStartShouldSetResponder={() => console.log("View click")}>
  // some code here
</View>