react.js 渲染一個列表的實例

//引入模塊
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
//定義一個要渲染的數組
let users=[
    {id:1,name:'老王1',age:31},
    {id:2,name:'老王2',age:32},
    {id:3,name:'老王3',age:33}
]
//定義一個User子組件
class User extends Component{
    //接收父組件傳遞過來的item
    render(){
        return(
            <tr>
                <td>{this.props.item.id}</td>
                <td>{this.props.item.name}</td>
                <td>{this.props.item.age}</td>
            </tr>
        )
    }
}
//在一個組件中,狀態越少越好
//定義一個UserList父組件
class UserList extends Component{
    //將父組件map映射出的每個item都傳遞給User子組件 ,key不用管,就是一個死的語句,防止報錯
    // 父組件下面user={users},將數組傳遞給父組件
    //全部父組件要接收這個數組 this.props.屬性名
    // 咱們將item傳遞給子組件User
    //裏面也須要接收this.props.item而後連綴就能夠拿到item下面的數據了this.props.item.id
    render(){
        return(
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>名字</th>
                    <th>年齡</th>
                </tr>
                </thead>
                <tbody>
                {
                    this.props.user.map((item,index)=>{
                    return (
                        <User item={item} key={index}></User>
                    )
                })
                }
                </tbody>
            </table>
        )
    }
}
//渲染到頁面上去
ReactDOM.render(<UserList user={users}></UserList>,document.querySelector("#root"));
相關文章
相關標籤/搜索