【问题标题】:add a condition in a list item在列表项中添加条件
【发布时间】:2021-05-05 10:58:06
【问题描述】:

我正在发布产品列表。我希望在显示时,我只保留产品名称的前 15 个字符,如果产品超过 15 个字符,则在此行的 15 个字符后自动显示'...' > { item.name.substring(0, 15)} 目前我是手动添加它们的,但我希望它可以通过条件“自动”完成;

是否可以添加此条件? 感谢您的帮助!

<ListItem
    style={{width:'100%', justifyContent: 'space-between'}}
    bottomDivider
    onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
    <Image source={{uri:URL+ item.photo}} 
           style={{ height: 25, resizeMode: 'contain'}}/>
    <ListItem.Title style={{width: '65%', fontSize: 16}}>{item.name.substring(0, 15)}...</ListItem.Title>
    <ListItem.Subtitle style={{ color: '#F78400'}}>{item.cost}€</ListItem.Subtitle>
  </ListItem>

【问题讨论】:

  • ListItem.Title 中有什么内容? ...是定制的吗?
  • 如果它是定制的,你使用Text。你可以使用numberOfLines 并在那里添加条件``` numberOfLines={condition ? firstFallback : secondOne}

标签: javascript list react-native conditional-statements


【解决方案1】:

要实现这种类型的阅读更多(字符数)... 类型的功能,您必须进行条件渲染,例如:

{
  ( item.name.length > 15 )  // Check if length is greater than certain length
  ?
  item.name.substring(0, 15) + ' ...'  // length is greater, show substring and ...
  :
  item.name  // show complete string
}

【讨论】:

    【解决方案2】:

    我猜你正在使用 React Native Elements...

    如果是这样,我建议您不要使用ListItem.Title,而是使用ListItem.Content,这样您就可以利用Text > numberOfLines 属性...它将截断文本并自动为您生成省略号...

    <ListItem.Content>
      <Text numberOfLines={1}>{item.name}</Text>
    </ListItem.Content>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2019-10-24
      • 2018-09-12
      • 2021-09-12
      • 2019-04-30
      • 2022-01-14
      • 1970-01-01
      相关资源
      最近更新 更多