reactjs - 如何显示数组的前三项并隐藏其他项?
问题描述
我对反应很陌生。我有很多评论。我怎样才能只显示这个数组中的前三个项目,而不是全部?
{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>
))}
解决方案
尝试这样的事情:
{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
。
希望这可以帮助 :)
推荐阅读
- amazon-web-services - GeoSpark Zeppelin 氦气插件
- ionic-framework - 离子框架中的Playstore问题
- sql - 在一行中查找并保留唯一值
- plugins - CKeditor5 - 插件 - 小部件 - 状态
- javascript - 如何在点击时用 JavaScript 替换 HTML 文档中两个常量之间的变量?
- sql - 我可以在一个查询中选择两个表吗?
- node.js - 如何在 Node js 中使用 Google Hangout 聊天 space.message.get 获取消息
- typo3 - 具有多个选项的表单元素的翻译
- android - 用于在 Android 6.0 上返回 null 的 firebase 读取数据的 addValueEventListener
- docker - 生产环境中 Ubuntu 上的最小 Kubernetes 集群