Skip to content

Instantly share code, notes, and snippets.

@luokailuo
Last active May 13, 2020 06:16
Show Gist options
  • Save luokailuo/dafe0f563d6b6d58e75a to your computer and use it in GitHub Desktop.
Save luokailuo/dafe0f563d6b6d58e75a to your computer and use it in GitHub Desktop.
React动态生成table
/**
* 引用React
*/
import React from 'react';
var DOM = React.DOM;
var table = DOM.table;
var tbody = DOM.tbody;
var tr = DOM.tr;
var td = DOM.td;
/**
* 使用DOM工厂方法创建Table
*/
class Table extends React.Component{
render() {
return table(null,tbody({
children: this.props.datas.map(function (data) {
return tr(null,
td(null, data.name),
td(null, data.age),
td(null, data.gender)
);
})
}));
}
}
/**
* 输出组件
*/
export default class CTable extends React.Component{
constructor(props){
super(props);
this.state = {
datas : [
{
'name': 'foo',
'age': 23,
'gender': 'male'
},
{
'name': 'bar',
'age': 25,
'gender': 'female'
},
{
'name': 'alice',
'age': 34,
'gender': 'male'
}
]
}
}
render() {
return (
<div>
<Table datas = {this.state.datas} />
</div>
)
}
}
import React from 'react';
/**
* 输出组件
*/
export default class Table extends React.Component{
constructor(props){
super(props);
this.state = {
data: [
{
un: 'Jacky',
phone: '13566668888',
age: 21
},
{
un: 'Mary',
phone: '13222223333',
age: 20
}
]
}
}
render() {
return (
<div>
<table>
<thead>
<tr>
<th>序号</th>
<th>用户名</th>
<th>手机号</th>
<th>年龄</th>
</tr>
</thead>
<Tbody data={this.state.data}/>
</table>
</div>
)
}
}
/**
* tbody
* 关键点是使用props来传递单向数据流。通过遍历从`props传来的数据data`生成表格的每一行数据
*/
class Tbody extends React.Component{
render() {
return (
<tbody>
{this.props.data.map(function (user, index) {
return <Item data={user} key={user.phone} index={index}/>
})}
</tbody>
)
}
}
/**
* td
* 每一行都需设置unique "key" prop
*/
class Item extends React.Component{
render() {
var key = this.props.key;
var index = this.props.index;
var data = this.props.data;
return (
<tr key={key}>
<td >{index + 1}</td>
<td>{data.un}</td>
<td>{data.phone}</td>
<td>{data.age}</td>
</tr>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment