簡體   English   中英

更改列表元素的順序

[英]Changing order of list elements

我想知道,如何更改某些列表中元素的順序。

例如,我將在下面列出此列表和用於更改順序的按鈕:

<button onClick={"function for moving the item up"}>Move Up</button>
<button onClick={"function for moving the item down"}>Move Down</button>

<ul>
  <li>Item1</li>
  <li className="selected-item">Item2</li>
  <li>Item3</li>
  <li>Item4</li>
</ul>

因此,如果我單擊“向上移動”按鈕,我希望類名為“selected-item”的項目向上移動(更改訂單位置)。 與單擊“下移”按鈕的情況完全相同,但項目當然會下移。

謝謝你。

我知道一種粗暴的做事方式。

  1. 首先,確保您的元素在列表中。
  2. 然后,允許選擇單個元素。
  3. 如果有選擇,只顯示移動按鈕。
  4. 更新當前和上一個或下一個元素的索引,交換它們。
  5. 由於狀態更新,應用程序以正確的方式重新呈現。

這是一個演示。

import React, { Component } from "react";
import "./styles.css";

export default class App extends Component {
  state = {
    items: ["Milk", "Curd", "Yogurt"],
    currentSelection: -1
  };
  selectHandler = (idx) => {
    let currentSelection = -1;
    if (this.state.currentSelection !== idx) {
      currentSelection = idx;
    }
    this.setState({
      currentSelection
    });
  };
  handleMove = (dir) => {
    const { currentSelection } = this.state;
    const items = [...this.state.items];
    if (dir === "up") {
      // Swap the currentSelection value with the previous one.
      let a = items[currentSelection];
      items[currentSelection] = items[currentSelection - 1];
      items[currentSelection - 1] = a;
    } else if (dir === "down") {
      // Swap the currentSelection value with the next one.
      let a = items[currentSelection];
      items[currentSelection] = items[currentSelection + 1];
      items[currentSelection + 1] = a;
    }
    this.setState({
      items,
      currentSelection: -1
    });
  };
  render() {
    const { items, currentSelection } = this.state;
    return (
      <div>
        <p>Click to select and again click to deselect.</p>
        <ul>
          {items.map((item, key) => (
            <li
              key={key}
              className={currentSelection === key ? "active" : undefined}
              onClick={() => this.selectHandler(key)}
            >
              {item}
            </li>
          ))}
        </ul>
        {currentSelection !== -1 && (
          <div>
            <p>What do you wanna do?</p>
            <button
              disabled={currentSelection === 0}
              onClick={(e) => {
                e.preventDefault();
                this.handleMove("up");
              }}
            >
              Move Up
            </button>
            <br />
            <button
              disabled={currentSelection === items.length - 1}
              onClick={(e) => {
                e.preventDefault();
                this.handleMove("down");
              }}
            >
              Move Down
            </button>
          </div>
        )}
      </div>
    );
  }
}

演示: https : //uiyq8.csb.app/

預覽

預覽

暫無
暫無

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

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