gpt4 book ai didi

reactjs - 如何根据不同的属性对 React 组件列表进行排序?

转载 作者:行者123 更新时间:2023-12-03 13:31:13 26 4
gpt4 key购买 nike

所以,这是我前端的代码片段。

{store.results.data.map( result =>
<ResultItem
key={result.id}
title={result.title}
description={result.description}
start_date={result.start_date}
end_date={result.end_date}
vendor_name={result.vendor.name}
buyer_name={result.buyer.name}
preview_file={result.preview_file}
status={result.status}
/>
)}

基本上,我将 Redux 存储中的所有数据映射到 ResultItems 中。我希望能够按不同的属性对所有 ResultItems 进行排序,例如 titledescriptionstart_dateend_datevendor_namebuyer_name

关于如何做到这一点有什么想法吗?

最佳答案

我将创建一个排序组件并用它包装结果项,如下所示:

<Sort by='title'>
{store.results.data.map( result =>
<ResultItem
key={result.id}
title={result.title}
description={result.description}
start_date={result.start_date}
end_date={result.end_date}
vendor_name={result.vendor.name}
buyer_name={result.buyer.name}
preview_file={result.preview_file}
status={result.status}
/>
)}
</Sort>

// Note: The 'by' prop passed into <Sort> in my example is hardcoded by you can grab it from redux or set it when user selects something from a list. Also you can pass another prop to indicate whether to sort by ascending or descending order etc

然后在 Sort 组件中,您可以访问像这样的结果项数组 React.Children.toArray 并使用数组的排序方法并向排序方法传递一个“比较”函数。

// Sort.js

import React from 'react';

// Compare function needed by the Sort component
const compare =(a, b) => {
// you can access the relevant property like this a.props[by]
// depending whether you are sorting by tilte or year, you can write a compare function here,

}

const Sort= ({children, by})=> {
If (!by) {
// If no 'sort by property' provided, return original list
return children
}
return React.Children.toArray(children).sort(compare)

}

上述的主要优点是您可以在其他任何地方使用排序组件,并且可以将排序逻辑与初始结果的映射完全分开。

关于reactjs - 如何根据不同的属性对 React 组件列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48764203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com