【问题标题】:Style breaks when using TouchableOpacity instead of TouchableWithoutFeedback使用 TouchableOpacity 而不是 TouchableWithoutFeedback 时样式中断
【发布时间】:2018-01-08 18:54:42
【问题描述】:

Here's how this part looks using TouchableWithoutFeedback

And here is the same thing, except with 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>

这是怎么回事?

【问题讨论】:

    标签: react-native touchableopacity


    【解决方案1】:

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

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

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

    之前:

    <TouchableOpacity onPress={...} style={styles.touchable}>
      // Touchable content
    </TouchableOpacity>
    

    之后:

    <TouchableWithoutFeedback onPress={...}>
      <View style={styles.touchable}>
        // Touchable content
      </View>
    </TouchableWithoutFeedback>
    

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

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

    【讨论】:

    • 谢谢!这是有道理的,但如果我想让我的 TouchableOpacity 表现得像 TouchableWithoutFeedback 一样呢?
    【解决方案2】:

    Nvm,我想通了。我基本上将TouchableOpacity 与外部View 进行了切换。所以,像这样:

    <View style={styles.buyCoinsItem}>
        <TouchableOpacity>      
            <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>
        </TouchableOpacity>
    </View>
    

    【讨论】:

      猜你喜欢
      • 2018-02-05
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 2017-11-17
      相关资源
      最近更新 更多