React Native: View onPress does not work
Solution 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>
Solution 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>
Solution 3:
Alternatively you can also provide onStartShouldSetResponder to your view, like so:
<View onStartShouldSetResponder={() => console.log("View click")}>
// some code here
</View>
Solution 4:
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>
Solution 5:
View doesn't provide onPress prop. Optional you can use
<View onStartShouldSetResponder={() => console.log("View click")}>
<Text>X</Text>
</View>
Else you can use TouchableOpacity
<TouchableOpacity onPress={this._onPress}>
<Text>X</Text>
</TouchableOpacity>