React Native: View onPress does not work

2020-05-12 04:37发布

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

4条回答
Viruses.
2楼-- · 2020-05-12 04:55

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>
查看更多
倾城 Initia
3楼-- · 2020-05-12 04:57

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

<View onStartShouldSetResponder={() => console.log("View click")}>
  // some code here
</View>
查看更多
甜甜的少女心
4楼-- · 2020-05-12 05:04

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>
查看更多
等我变得足够好
5楼-- · 2020-05-12 05:15

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>

查看更多
登录 后发表回答