React实现table根据不同字段升降序排序

tableBox.html: <!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="tableBox.css"><script src="build/react.js"></script>&lt...

tableBox.html:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="tableBox.css">
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<script src="build/browser.min.js"></script>
</head>
<body>
<div id="tableBox"></div>
<script type="text/babel" src="tableBox.jsx"></script>
</body>
</html>


tableBox.jsx:

var data = [
{name: "Bruce", age: 23, id: 16, score: 80},
{name: "Alice", age: 24, id: 12, score: 90},
{name: "David", age: 21, id: 11, score: 70},
{name: "Cindy", age: 22, id: 10, score: 100},
];
var flag = {
name: true,
age: true,
id: true,
score: true
};
function upSort(propertyName) {
if ((typeof data[0][propertyName]) != "number") {
return function(object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
return value1.localeCompare(value2);
}
}
else {
return function(object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
return value1 - value2;
}
}

function downSort(propertyName) {
if ((typeof data[0][propertyName]) != "number") {
return function(object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
return value2.localeCompare(value1);
}
}
else {
return function(object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
return value2 - value1;
}
}

var TableBox = React.createClass({
getInitialState: function() {
return {data:this.props.data};
},
sort: function(e) {
var prop = e.target.innerHTML;
if (flag[prop] == true)
this.state.data.sort(upSort(prop));
else
this.state.data.sort(downSort(prop));
flag[prop] = !flag[prop];
this.setState({data:this.state.data});
},
render: function() {
return (
<table>
<thead>
<tr>
<th onClick={this.sort}>name</th>
<th onClick={this.sort}>age</th>
<th onClick={this.sort}>id</th>
<th onClick={this.sort}>score</th>
</tr>
</thead>
<tbody>
{
this.state.data.map(function(item, index) {
return (
<tr key={index}>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.id}</td>
<td>{item.score}</td>
</tr>
);
})
}
</tbody>
</table>
);
}
})
ReactDOM.render(
<TableBox data={data}/>, 
document.getElementById("tableBox")
);

JavaScript对象数组根据某属性sort升降序排序的具体实现请见:http://www.shehuiyuan.com/article/172

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章