React Native检测点击View

Hum*_*01d 10 react-native

我正在写一个React Native应用程序,我想检测屏幕上任何位置的点击/点击,所以我在我的<View>元素上放了一个onClick处理程序,但它似乎没有工作.这是我的渲染功能:

<View style={styles.container} onClick={this.onClick}>
    <Text style={styles.welcome}>
        Tap to change the background
    </Text>
</View>
Run Code Online (Sandbox Code Playgroud)

我需要做什么?

小智 22

要使任何元素处理React-Native UI中的触摸/单击事件,您需要将元素放在TouchableOpacity,TouchableWithoutFeedback,TouchableNativeFeedback或TouchableHighlight元素中:

<TouchableHighlight onPress = { this.onClick }>
    <View style={styles.container}>
    <Text style={styles.welcome}>
        Tap to change the background
    </Text>
    </View>
</TouchableHighlight>
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


And*_*iko 15

在React Native版本> 55.3中,如果使用onStartShouldSetResponder道具,则将onPress事件检查到View中.

像例子:

<View 
    style={{ flex: 1 }}
    onStartShouldSetResponder={() => console.log('You click by View')}
 >

    <ScrollView 
        refreshControl={
           <RefreshControl 
               refreshing={this.state.refreshing}
               onRefresh={this.onRefresh} />
           }
      >

     <Text>Awesome</Text>

    </ScrollView>
</View>
Run Code Online (Sandbox Code Playgroud)

在示例中,我展示了如何在View上获取onPress事件,而不是阻止其后的其他事件.刷新控制仍然正常.


Rom*_*man 11

在我的情况下,以下工作正常。您可以在任何via props上使用onTouchStartonTouchEnd处理程序View,例如:

<View onTouchStart={() => this.doSomething()} />
Run Code Online (Sandbox Code Playgroud)

更多信息