【问题标题】:How to sort react components based on props being passed into it如何根据传入的道具对反应组件进行排序
【发布时间】:2020-04-08 23:56:34
【问题描述】:

我有这个组件 SingleEmail,我将道具传递给例如 emailSubject、emailFrom、emailDate、emailBody。我试图弄清楚如何对格式为 2020 年 4 月 8 日的日期进行升序和降序排序。

我设置


  <Sort by="emailDate">
            <div className="IncomingArea">
              {this.state.data.map((value, index) => (
                <SingleEmail
                  Subject={value.emailSubject}
                  From={value.emailFrom}
                  Date={value.emailDate}
                  Body={value.emailBody}
                />
              ))}
            </div>
          </Sort>

一个名为 Sort 的组件包裹在我的 SingleEmail 组件周围


// 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);
};

export default Sort;

基本上我想弄清楚从这里到哪里去,以便能够根据 emailDate 值按日期 asc 和 desc 排序。我在带有 SingleEmail 组件的页面上设置了两个按钮,因此我可以为一个用于 asc 和一个用于 desc 添加一个 onClick。只是对如何让这个排序组件提供状态或任何需要的东西感到困惑,所以如果有意义的话,我可以使用它们进行排序。任何帮助将不胜感激=]希望这不是一个太笼统的问题=p

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    当您可以使用标准 Array 的排序方法对您拥有的数据进行排序时,我不确定为什么需要 Sort 组件。

    请注意,您需要将字符串转换为 Dates 对象以便比较它们:

    data.sort((a, b)=>{return new Date(a.emailDate) - new Date(b.emailDate)})
    

    你的代码应该是这样的:

    <div className="IncomingArea">
        {
            this.state.data.sort(
                (a, b) => {
                    return new Date(a.emailDate) - new Date(b.emailDate)
                }).map((value, index) => (
                <SingleEmail
                    Subject={value.emailSubject}
                    From={value.emailFrom}
                    Date={value.emailDate}
                    Body={value.emailBody}
                />
            ))}
    </div>
    

    【讨论】:

    • 不,为什么在按钮的点击中需要这个?你检查我的答案了吗?
    • 我不好,这是一个愚蠢的问题哈哈
    • 你看到我的反应例子了吗? javascript one-liner 下方的两行。你拥有一切......
    • 呃,今天不是我的日子,我怎么错过了,谢谢伙计
    猜你喜欢
    • 2020-05-25
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多