簡體   English   中英

如何在 React 中對 HTML 表格進行排序?

[英]How to sort an HTML table in React?

我有一個包含數字、日期和字符串的表。 我希望能夠通過單擊表格的標題對它們進行排序,並讓它們按特定單擊的標題進行排序,但是我在執行此操作的邏輯上遇到了問題。 我已經閱讀了其他堆棧溢出的答案,但它們對我應該做什么有些困惑。 有人可以指出我正確的方向嗎?

Function 

 const sorted = () => {
        const arr = []
        const tableBody = document.getElementsByTagName('table')
        const tableRow = document.getElementsByTagName('tr')
        const tableHeader = document.querySelectorAll('th');
        console.log(tableBody)

        for (let i = 0; i < tableHeader.length; i++) {
            tableHeader[i].addEventListener('click', () => {
                console.log(tableBody)
            })
        }

    }
    sorted()

Table

 <div className="outputs" >
                <table>
                    <tr>
                        <th>Date</th>
                        <th>Stock Name</th>
                        <th>Price Of Option</th>
                        <th>Number Of Options</th>
                        <th>Total Amount Spent</th>
                        <th>Option Sold At</th>
                        <th>Amount Of Options Sold</th>
                        <th>Proft</th>
                    </tr>
                    {listOfOptions.map(option => {
                        return (
                            <tbody>
                                <tr>
                                    <td>{option.clock}</td>
                                    <td>{option.name.toUpperCase()}</td>
                                    <td>${option.price}</td>
                                    <td>{option.amountOfOptions}</td>
                                    <td>${option.totalAmountSpent.toFixed(2)}</td>
                                    <td>${option.optionPriceSoldAt}</td>
                                    <td>{option.amountOfOptionsSold}</td>
                                    <td style={{ color: option.totalProfit >= 0 ? 'green' : 'red' }}>${option.totalProfit.toFixed(2)}</td>
                                </tr>
                            </tbody>
                        )
                    })}
                </table>
            </div>

正如我所見——

  • 在每個或一個包裝所有內容上添加處理程序
  • 在處理程序中獲取列名並按此名稱對 listOfOptions 進行排序(在它之前,將列名映射到鍵,例如:選項的價格 -> 價格等...)
  • 使用鈎子 (useState) 或 setState 將新的 sortedArray 設置為 state 並重新渲染組件

采取的步驟是:

  1. 將數組存儲在局部變量listOfOptions
  2. 將點擊處理程序附加到表格的標題元素
  3. 在這些處理程序中,對數組進行排序並用新的排序數組替換舊數組。

我只實現了兩個標題單擊處理程序,但應該足以了解總體思路。

import React, { useState } from "react";


export default function App() {
  const [listOfOptions, setListOfOptions] = useState([
    {
      clock: "23/12/2020",
      name: "Dorothy",
      price: 12.34,
      amountOfOptions: 1,
      totalAmountSpent: 23.3232,
      optionPriceSoldAt: 34.22323,
      amountOfOptionsSold: 122.34,
      totalProfit: 44433.343
    },
    {
      clock: "23/12/2020",
      name: "Brian",
      price: 12.34,
      amountOfOptions: 2,
      totalAmountSpent: 255.3232,
      optionPriceSoldAt: 52.194323,
      amountOfOptionsSold: 622.34,
      totalProfit: 9433.343
    },
    {
      clock: "23/12/2020",
      name: "Alfred",
      price: 12.34,
      amountOfOptions: 3,
      totalAmountSpent: 123.3232,
      optionPriceSoldAt: 12.22323,
      amountOfOptionsSold: 72.34,
      totalProfit: 5433.343
    }
  ]);

  function sortByNumberOfOptions() {
    const clonedOptions = [...listOfOptions];

    clonedOptions.sort((a, b) => {
      return a.amountOfOptions  - b.amountOfOptions;
    });

    setListOfOptions(clonedOptions);
  }

  function sortByName() {
    const clonedOptions = [...listOfOptions];

    clonedOptions.sort((a, b) => {
      if (a.name > b.name) {
        return 1;
      } else if (a.name < b.name) {
        return -1;
      }
      return 0;
    });

    setListOfOptions(clonedOptions);
  }

  return (
    <div>
      <div className="outputs">
        <table>
          <tr>
            <th>Date</th>
            <th onClick={sortByName}>Stock Name</th>
            <th>Price Of Option</th>
            <th onClick={sortByNumberOfOptions}>Number Of Options</th>
            <th>Total Amount Spent</th>
            <th>Option Sold At</th>
            <th>Amount Of Options Sold</th>
            <th>Proft</th>
          </tr>

          <tbody>
            {listOfOptions.map((option, index) => {
              return (
                <tr key={index}>
                  <td>{option.clock}</td>
                  <td>{option.name.toUpperCase()}</td>
                  <td>${option.price}</td>
                  <td>{option.amountOfOptions}</td>
                  <td>${option.totalAmountSpent.toFixed(2)}</td>
                  <td>${option.optionPriceSoldAt}</td>
                  <td>{option.amountOfOptionsSold}</td>
                  <td
                    style={{ color: option.totalProfit >= 0 ? "green" : "red" }}
                  >
                    ${option.totalProfit.toFixed(2)}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}


StackBlitz 版本在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM