現在需要在頁面上顯示一本書的章節,章節內容存放到一個數組里面:
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' }
...
]
現在需要你構建兩個組件。一個組件為 Lesson
組件,渲染特定章節的內容。可以接受一個名為 lesson
的 props
,并且把章節以下面的格式顯示出來:
<h1>Lesson 1: title</h1>
<p>Lesson 1: description</p>
點擊每個章節的時候,需要把章節在列表中的下標和它的標題打印(console.log)
出來,例如第一個章節打印:0 - Lesson 1: title
,第二個章節打印:1 - Lesson 2: title
。
另外一個組件為 LessonsList
,接受一個名為 lessons
的 props
,它會使用 Lesson
組件把章節列表渲染出來。
class Lesson extends Component {
/* TODO */
constructor(props){
super(props)
}
handleClick(){
console.log(this.props._index + ' - ' + this.props.lesson.title)
}
render(){
return (
<div onClick={this.handleClick.bind(this)}>
<h1>{this.props.lesson.title}</h1>
<p>{this.props.lesson.description}</p>
</div>
)
}
}
class LessonsList extends Component {
/* TODO */
constructor(props){
super(props)
}
render(){
return (
<div>
// 不要忘記 {}
{this.props.lessons.map(function(lesson, index){
return (<Lesson key={index} _index={index} lesson={lesson} />)
})}
</div>
)
}
}