使用 TouchableOpacity 而不是 TouchableWithoutFeedback 时样式会中断

Bor*_*ito 5 react-native touchableopacity

这是使用 TouchableWithoutFeedback 时这部分的外观

这是同样的事情,除了 TouchableOpacity

这部分的代码:

<TouchableWithoutFeedback>
    <View style={styles.buyCoinsItem}>
        <View style={styles.cost}>
            <Text>{no_of_coins}</Text>
        </View>
        <Text>{product.priceString}</Text>
        <View style={{height:30, flexDirection: 'row', marginTop:10}}>
            {displayDiscount && 
            <View style={styles.discountContainer}>
                <Text style={styles.whiteText}>Save {discount}</Text>
            </View>
            }
        </View>
    </View>
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

jev*_*lio 7

这是如何实现这两个组件的一个令人讨厌的副作用。

本质上,它TouchableOpacity是一个原生支持的视图,它通过调用setNativeProps({ opacity })该视图来支持触摸交互,而TouchableWithoutFeedback它只是简单地包装了一个原生视图并附加了触摸处理程序。

为了使TouchableWithoutFeedback行为像TouchableOpacity,在其中嵌套一个额外的View,并在子视图上定义任何样式:

前:

<TouchableOpacity onPress={...} style={styles.touchable}>
  // Touchable content
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

后:

<TouchableWithoutFeedback onPress={...}>
  <View style={styles.touchable}>
    // Touchable content
  </View>
</TouchableWithoutFeedback>
Run Code Online (Sandbox Code Playgroud)

我不确定为什么 API 是这样设计的 - 我的猜测是避免在不需要时出于性能原因创建额外的本机支持视图。

然而,从重构的目的来看,这使得在不同类型的 Touchables 之间移动变得更加痛苦。在我的项目中,我通常会创建一个自定义的 Touchable 组件,将这个逻辑包装在一个 prop 之后,或者使用类似react-native-platform-touchable 的东西,它可以在 Android 上为您提供 Android Material 风格的效果。