react數據渲染


現在需要在頁面上顯示一本書的章節,章節內容存放到一個數組里面:

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{
   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 LessonList extends Component{
    render(){
        return(
            <div>
            {this.props.lessons.map((lesson,id)=>{
               return <Lesson lesson={lesson} id={id}/>
            })}
            <div/>
        )
        
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM