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

本文探讨了如何在React中利用JavaScript对象数组的sort方法,针对table的特定字段实现升序和降序排序功能。详细步骤和示例代码参考链接:http://blog.youkuaiyun.com/zhouziyu2011/article/details/71189124。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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://blog.youkuaiyun.com/zhouziyu2011/article/details/71189124

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值