React:如何从头开始创建可重新排序的列表
本文向您展示了如何在 React 中从头开始创建可排序列表。我们将使用现代 React 特性,如钩子和函数式组件。不需要第三方库。
在绝大多数情况下,当我们渲染一个列表时,数据源将是一个对象数组。我们需要做的是按照某个属性的升序或降序排列这些对象。例如,您想按价格从低到高或从高到低的顺序对产品列表进行排序,按年龄对用户进行排序,按薪水对公司中的员工进行排序等等。幸运的是,在Javascript中,我们可以很方便地得到这份工作通过利用Array.sort() 方法完成,如下所示:
// sort by price in ascending order
sortedProducts = products.sort((a, b) => a.price - b.price)
或者像这样:
// sort by price in descending order
sortedProducts = products.sort((a, b) => b.price - a.price)
为了更清楚起见,请检查下面的完整示例。
例子
演示
我们要构建的应用程序模拟了主要电子商务平台的一个功能,即按价格升序或降序对产品进行排序。在列表的正上方,有一个带有 3 个选项的选择元素:
- 默认
- 价格从低到高
- 价格从高到低
每次更改所选选项时,都会呈现列表。以下是它的工作原理:
代码
1.初始化一个新项目:
npx create-react-app kindacode-example
你可以选择任何你喜欢的名字。没关系。
2. src/App.js中的完整源代码及解释:
// KindaCode.com
// src/App.js
import { useState } from 'react';
// import CSS
import './App.css';
// dummy data
const products = [
{ id: 'p1', name: 'Apple', price: 10 },
{ id: 'p2', name: 'Banana', price: 8 },
{ id: 'p3', name: 'Water Melon', price: 7 },
{ id: 'p4', name: 'Coconut', price: 6.99 },
{ id: 'p5', name: 'Peach', price: 5.99 },
{ id: 'p6', name: 'Guava', price: 4 },
{ id: 'p7', name: 'Cucumber', price: 12 },
{ id: 'p8', name: 'Papaya', price: 18.99 },
{ id: 'p9', name: 'Jackfruit', price: 15.5 },
];
function App() {
// sorted products list
// in the beginning, the order id default
const [sortedProducts, setSortedProducts] = useState(products);
// the sorting function
const sortHandler = (e) => {
const sortType = e.target.value;
// deep copy the products array
const arr = [...products];
// sort by price in ascending order
if (sortType === 'asc') {
setSortedProducts(arr.sort((a, b) => a.price - b.price));
}
// sort by price in descending order
if (sortType === 'desc') {
setSortedProducts(arr.sort((a, b) => b.price - a.price));
}
// restore the default order
if (sortType === 'default') {
setSortedProducts(arr);
}
};
return (
<div className='container'>
<h2>Welcome to KindaCode's Fiction Shop</h2>
{/* This select element is used to sort the list */}
<select onChange={sortHandler} className="select">
<option value='default'>Default</option>
<option value='asc'>Price Low To High</option>
<option value='desc'>Price High To Low</option>
</select>
{/* Render the product list */}
<div className='list'>
{sortedProducts.map((product) => (
<div key={product.id} className='product'>
<div>{product.name}</div>
<div>${product.price}</div>
</div>
))}
</div>
</div>
);
}
export default App;
- 不要忘记将src/App.css中的所有默认代码替换为以下内容:
.container {
width: 80%;
margin: 40px auto;
}
.select {
width: 200px;
}
/* Style the list */
.list {
margin-top: 30px;
width: 600px;
}
.product {
display: flex;
justify-content: space-between;
padding: 10px 30px;
font-size: 16px;
}
.product:nth-child(odd) {
background: #fffce2;
}
.product:nth-child(even) {
background: #e2f6ff;
}
- 启动并运行项目:
npm start
并转到 http://localhost:3000 检查结果。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。