React Native:View onPress 不起作用

React Native: View onPress does not work

我遇到了一个奇怪的问题。在我的 React 本机应用程序中,如果我将 onPress 事件设置为 View,它不会被触发,但如果我在 View 中将其设置为 Text,它就会触发。我在这里错过了什么?

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

为什么会这样?这是 React Native 的问题吗?我使用的是版本 0.43

您可以将 TouchableOpacity 用于 onPress 事件。 View 不提供 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、TouchableNativeFeedback 来实现这一点。视图组件不提供 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>

2021

If you're looking for a more extensive and future-proof way to handle touch-based input, check out the Pressable API.

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

在视图中 onPress 将不起作用,因为视图不支持 onPress 事件 tag.That 是它不起作用的原因,但您可以转到此 link https://reactnative.dev/docs/view

react native 0.67新增了一个可按压组件,可以解决你的问题。它在任何地方运行 enter image description here

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

touchable(opacity,withoutfeedback,....)

Pressable 当前在 react native 包中可用的组件,例如,

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

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