簡體   English   中英

Pressable 和 TouchableWithoutFeedback 之間的差異

[英]Differences between Pressable and TouchableWithoutFeedback

Pressable 和 TouchableWithoutFeedback 是向其子項添加觸摸功能的高階組件。 他們有非常相似的用例。 我想我可以在任何地方使用 Pressable 代替 TouchableWithoutFeedback(由於官方文檔推薦)。

但問題是,有時他們的行為會有所不同。 例如,當我用 Pressable 替換 TouchableWithoutFeedback 時,布局會發生變化。 我不知道是什么原因造成的,但我認為 Pressable 就像一個單獨的視圖,而 touchablewithoutfeedback 則不是。

除了道具不同之外,你能明確指出這兩者之間的區別嗎?

這是他們行為不同的地方:

列表項.js

const ListItem = (props) => {
  return (
    <Pressable onPress={props.onPress}>
      <View style={[styles.container, props.style]}>
        <View style={styles.startSection}>
          {props.renderStart && <View style={{marginEnd: 12}}>{props.renderStart}</View>}

          <View style={styles.textSection}>
            <Text >{props.title}</Text>
            {props.subTitle && (
              <View style={styles.subTitleContainer}>
                {props.subTitleIcon && (
                  <SVGIcon
                    icon={props.subTitleIcon(props.subTitleColor || Colors.primaryColor)}
                    width={12}
                    height={12}
                    style={styles.subTitleIcon}
                  />
                )}
                <Text style={{color: props.subTitleColor || Colors.primaryColor}}>
                  {props.subTitle}
                </Text>
              </View>
            )}
          </View>
        </View>

        <View style={styles.endSection}>{props.renderEnd}</View>
      </View>
    </Pressable>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    paddingHorizontal: 12,
    paddingVertical: 8,
    minHeight: 48,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  startSection: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  textSection: {
    flexDirection: 'column',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  subTitleContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 3,
  },
  subTitleIcon: {
    marginEnd: 5,
  },
  endSection: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
});

應用程序.js

<ListItem
  title="group"
  renderEnd={
    <TouchableWithoutFeedback  // this works fine, but Pressable doesn't work here
        onPress={onListItemPress}>{chevronIcon()}
    </TouchableWithoutFeedback>
  }
  onPress={onListItemPress}
/>

這里 TouchableWithoutFeedback 工作正常,但 Pressable 不調用 onPress。

我認為您可以在 SO 中的這個問題中找到答案。 有關更多信息,您可以在Medium上查看這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM