[英]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”的項目向上移動(更改訂單位置)。 與單擊“下移”按鈕的情況完全相同,但項目當然會下移。
謝謝你。
我知道一種粗暴的做事方式。
這是一個演示。
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.