反应本机: 视图 onPress 不工作

我遇到了一个奇怪的问题。在我的反应本机应用程序,如果我设置 onPress事件为 View,它不会被触发,但如果我设置相同的 Text内的 View,它触发。我错过了什么?

<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>

为什么会这样? 这是反应原生的问题吗? 我使用的是0.43版本

131738 次浏览

可以对 onPress事件使用 TouchableOpacityView不提供 onPress道具。

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

你可以用 TouchableWithoutFeedback包装视图,然后像往常一样使用 onPress和朋友。你还可以通过在子视图上设置属性来阻止 pointerEvents,它甚至可以阻止父 TouchableWithoutFeedback上的指针事件,这很有趣,这是我在 Android 上的需要,我没有在 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>

您可以使用 TouchableOpacity、 TouchableHighlight、 TouchableNativeFeedi 来实现这一点。视图组件不提供 onPress 作为道具。所以你用这个代替那个。

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


OR


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


OR


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

或者,您也可以为视图提供 onStartShouldSetResponder,如下所示:

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

对于任何寻找解决方案的人来说,截至 RN 0.63,有一个新的 Pressabe api。它可能早些时候推出了几个版本,但是对于这样的用例来说,它工作得非常好。

<Pressable onPress={onPressFunction}>
<Text onPress={() => {
console.log('works');
}}>X</Text>
</Pressable>

OnPress 不能在 <View>标签上工作,使用 <TouchableOpacity>代替 View

<View>
<TouchableOpacity onPress={() => 'call your function here'}>
</TouchableOpacity>
</View>

我们可以使视图有一个 onPress 道具 OnStartShouldSetResponderOnResponderGrant

<View
onStartShouldSetResponder={() => true}
onResponderGrant={() => console.log("view pressed")}
>
</View>

您可以为此目的使用 TouchableOpacity

<TouchableOpacity onPress={() => {your code here}}>
//Your inner views here
</TouchableOpacity>

二零二一年

如果您正在寻找一种更加广泛和未来的方式来处理基于触摸的输入,请查看 可压制的 API。

资料来源: https://reactnative.dev/docs/touchablewithoutfeedback

在视图中 onPress 将无法工作,因为在视图标记中不支持 onPress 事件。这就是为什么它不工作,但你可以去这个链接 https://reactnative.dev/docs/view

一个新的可压缩组件提供了0.67的本地反应,这可以解决你的问题。它运行在任何地方 在此输入图像描述

对于这个问题,您可以使用

touchable(opacity,withoutfeedback,....)

Pressable组件,目前可在反应本地包,如,

<TouchableOpacity onPress={()=>console.log("Pressed")}>
....
</TouchableOpacity>

或者

<Pressable onPress={()=>console.log("Pressed")}>
....
</Pressable>