我做了一个简单的代码复制.我有一个列表,我可以通过单击up down按钮来更改项目位置.我想实现也是一个动画时,改变项目的立场.因此,例如,点击"向上"按钮应移动项目translateY(-100%)
和"向下"按钮的其他方式. 我自己试过这个,但是没有达到效果,而且在改变位置的时候有很多bug.做这件事的最好方法是什么?
const { useState } = React;
const ITEMS = ["item 1", "item 2", "item 3", "item 4"];
const App = () => {
const [items, setItems] = useState(ITEMS);
const handleMoveItem = (index, direction) => {
const updatedItems = [...items];
const targetIndex = direction === "up" ? index - 1 : index + 1;
if (targetIndex >= 0 && targetIndex < items.length) {
[updatedItems[index], updatedItems[targetIndex]] = [
updatedItems[targetIndex],
updatedItems[index],
];
setItems(updatedItems);
}
};
return (
<div className="wrapper">
<ul>
{items.map((item, index) => (
<li key={item}>
{item}
<div>
<button onClick={() => handleMoveItem(index, "up")}>
up
</button>
<button onClick={() => handleMoveItem(index, "down")}>
down
</button>
</div>
</li>
))}
</ul>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
.wrapper {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
ul {
list-style: none;
width: 500px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 1rem;
}
ul li {
text-align: center;
display: flex;
justify-content: space-between;
background-color: lightblue;
transition: transform 0.3s ease;
}
<div id="root">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js"></script>
</div>