您的位置:首页 > Web前端 > React

react.js 渲染一个列表的实例

2017-09-19 12:18 429 查看
//引入模块
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"));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: