React遍历数组仅渲染单个FeedbackItem组件问题求助
问题解决:遍历数组仅渲染单个FeedbackItem的原因及修复方案
问题描述
遍历feedbackData数组生成FeedbackItem组件,预期显示3个条目,但实际仅能看到1个。
核心问题分析
- 组件重叠导致视觉上仅显示1个:
.feedbackItem的CSS设置了position: absolute,这会让所有组件脱离正常文档流,被定位到相同位置,互相重叠,看起来只显示了1个。 - 内容缺失:
FeedbackItem组件中,评论文本<p className='review'>未渲染item.text,即使组件正常显示,也看不到评论内容。
修复方案
1. 修正CSS定位问题
移除.feedbackItem的绝对定位,改用正常文档流布局,同时调整margin让条目之间保持间距:
.feedbackItem{ border-radius: 20px; background-color: aquamarine; width: 50vw; height: 20vh; /* 移除position: absolute */ margin: 20px 0 20px 50px; /* 调整上下margin,避免条目紧贴 */ }
2. 补全评论内容渲染
在FeedbackItem组件中,将item.text渲染到对应的元素中:
import React from 'react' function FeedbackItem({item}) { return ( <div className='feedbackItem'> <p className='rating'> {item.rating}</p> <p className='review'>{item.text}</p> {/* 渲染item的text内容 */} </div> ) } export default FeedbackItem
可选优化:优化列表容器布局
若需要更规整的垂直排列,可给.showfeedback添加flex布局:
.showfeedback{ flex: 6; display: flex; flex-direction: column; padding: 20px 0; }
修复效果验证
修改完成后,3个FeedbackItem会垂直排列显示,每个条目都能看到对应的评分和评论内容,不会再出现重叠情况。
内容的提问来源于stack exchange,提问作者krishna
相关产品推荐
相关产品推荐

