首页 > 解决方案 > 如何显示数组的前三项并隐藏其他项?

问题描述

我对反应很陌生。我有很多评论。我怎样才能只显示这个数组中的前三个项目,而不是全部?

{item.Comments.map((item, key) => (
  <View key={key} style={{marginVertical:10,marginLeft:12}}>
    <View style={{flexDirection:"row"}}>
      <Text style={{color:"rgba(0,0,0,0.7)"}}> {item.username}</Text>
    </View>
    <Text style={{padding:5}}> {item.comment}</Text>
  </View>
))}

标签: reactjsreact-native

解决方案


尝试这样的事情:

{item.Comments.slice(0,3).map((item, key) => (
  <View key={key} style={{marginVertical:10,marginLeft:12}}>
    <View style={{flexDirection:"row"}}>
      <Text style={{color:"rgba(0,0,0,0.7)"}}> {item.username}</Text>
    </View>
    <Text style={{padding:5}}> {item.comment}</Text>
  </View>
))}

请注意,我所做的唯一更改是.slice(0,3)在使用之前添加.map- 这将获取item.Comments数组的前 3 个元素(请参阅slice文档),然后您可以立即调用.map该数组的 3 个项目。item.Comments如果您的数组以某种方式少于 3 个项目,它甚至可以工作:D

注意:函数中的第二个参数.map是您要映射的数组中的当前索引,因此在您调用参数的地方key,通常人们会调用它index,并且仍然将其分配给组件中的key属性View

希望这可以帮助 :)


推荐阅读