我正在尝试使用json文件将内容添加到组件中,在该文件中,我只需要第一个组件具有封面图像,其余组件则忽略它。
Schema: "TrackList": [
{
"CourseNo": "1",
"CourseName": "C++ Programming with DataStructures",
"CoverImg":"example.com/cover.jpg"
},
{
"CourseNo": "2",
"CourseName": "Competitive Programming"
},
{
"CourseNo": "3",
"CourseName": "Java"
}
]
下面的代码根据需要进行渲染,但它还会将空白图像添加到第一个组件之外的组件中。
render(){
const { Data } = this.props;
const Courses = Data.TrackList.map(course => {
return (
<li>
<span>Course {course.CourseNo}</span>
<a href='#path-10'>{course.CourseName}</a>
<img src={course.CoverImg}/>
</li>
)
});
return(
<div className='col-md-4 right-pannel'>
<ul>
{Courses}
</ul>
</div>
)
}
Array.prototype.map
使用当前数组索引调用提供的回调函数。数组的第一个索引为Array.prototype.map
,因此您只需添加一些逻辑以确保仅在索引等于0时才添加图像,如下所示:
0
这是您的代码的略微修改版本,变成了可运行的代码段:
const Courses = Data.TrackList.map((course, i) => {
return (
<li>
<span>Course {course.CourseNo}</span>
<a href='#path-10'>{course.CourseName}</a>
{ i === 0 && <img src={course.CoverImg}/> }
</li>
)
});
const Data = {"TrackList": [{"CourseNo": "1","CourseName": "C++ Programming with DataStructures","CoverImg":"example.com/cover.jpg"},{"CourseNo": "2","CourseName": "Competitive Programming"},{"CourseNo": "3","CourseName": "Java"}]}
const Courses = Data.TrackList.map((course, i) =>
<li>
<span>Course {course.CourseNo}</span>
<span>{course.CourseName}</span>
{ i === 0 && <span>{course.CoverImg}</span> }
</li>
);
ReactDOM.render(
<div className='col-md-4 right-pannel'>
<ul>
{Courses}
</ul>
</div>,
document.body
)
或更通用的解决方案可以是下面的代码,如在您的数据中可以看到的,其他对象没有CoverImg键。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>