React Native:查看onPress不起作用

meh*_*mpt 85 react-native react-native-android

我面临着一个奇怪的问题.在我的本机应用程序中,如果我将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>
Run Code Online (Sandbox Code Playgroud)

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

Ahs*_*Ali 144

你可以TouchableOpacity用于onPress活动. View不提供onPress道具.

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

  • 完整的参考文档在这里:https://facebook.github.io/react-native/docs/touchableopacity.html (2认同)

Noi*_*art 22

您可以使用a包装视图,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>
Run Code Online (Sandbox Code Playgroud)

  • 在iOS上进行了测试,效果很好。可触摸但无反馈且可触摸突出显示 (2认同)

Syd*_* C. 8

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

<View onStartShouldSetResponder={() => console.log("View click")}>
  // some code here
</View>
Run Code Online (Sandbox Code Playgroud)


小智 6

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

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

OR

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

OR

<TouchableOpacity onPress={this._onPressButton}>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)


小智 6

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

touchable(opacity,withoutfeedback,....)
Run Code Online (Sandbox Code Playgroud)

Pressable当前在 React Native 包中可用的组件,例如,

<TouchableOpacity onPress={()=>console.log("Pressed")}>
  ....
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

或者

<Pressable onPress={()=>console.log("Pressed")}>
  ....
</Pressable> 
Run Code Online (Sandbox Code Playgroud)


小智 5

onPress 不适用于<View>标签<TouchableOpacity>而不是视图

<View>
<TouchableOpacity onPress={() => 'call your function here'}>
</TouchableOpacity>
</View>
Run Code Online (Sandbox Code Playgroud)