react的列表渲染比vue稍微麻烦一点。
首先在一个组件写单个的写法,然后在一个大的组件里通过props使用map依次渲染列表中的数据(注意加key)。如下
class Lesson extends Component {
/* TODO */
render(){
const {lesson}=this.props
return (
<div onClick={()=>{
console.log(this.props.index+ ' - ' + lesson.title)
}}>
<h1>{lesson.title}</h1>
<p>{lesson.description}</p>
</div>
)
}
}
class LessonsList extends Component {
/* TODO */
render(){
return (
<div>
{this.props.lessons.map((lesson,index) => <Lesson lesson={lesson} key={index} index={index}/>)}
</div>
)
}
}
这样外部只要在LessonList组件中传lessons(对象数组)即可,如:
const lessons = [
{ title: 'Lesson 1: title', description: 'Lesson 1: description' },
{ title: 'Lesson 2: title', description: 'Lesson 2: description' },
{ title: 'Lesson 3: title', description: 'Lesson 3: description' },
{ title: 'Lesson 4: title', description: 'Lesson 4: description' }
]
ReactDOM.render(
<LessonsList lessons={lessons}/>,
document.getElementById('root')
)