React列表重排改造咨询:将上下点击重排改为左右点击重排(附代码)
改造React列表项为左右点击重排的实现方案
嘿,这事儿其实挺简单的,核心逻辑和你之前的上下移动几乎一致,只是把方向标识和交互按钮换成左右方向就行。我给你整理了具体的改造步骤和完整代码:
核心思路
上下移动和左右移动本质都是调整数组元素的索引位置,所以handleMove函数的逻辑完全可以复用,只需要把方向常量的名字改得更贴合左右场景,同时替换掉交互用的箭头图标就行。
改造步骤&代码
1. 调整App组件
把原来的UP/DOWN常量改成LEFT/RIGHT(值还是-1和1,因为左移对应索引减1,右移对应索引加1),函数逻辑不用动:
import React from "react"; import FruitList from "./FruitList"; // 替换方向常量为左右 const LEFT = -1; const RIGHT = 1; class App extends React.Component { state = { items: [ { id: 1, name: "orange", bgColor: "#f9cb9c" }, { id: 2, name: "lemon", bgColor: "#fee599" }, { id: 3, name: "strawberry", bgColor: "#e06666" } ] }; handleMove = (id, direction) => { const { items } = this.state; const position = items.findIndex(i => i.id === id); if (position < 0) { throw new Error("Given item not found."); } // 边界判断:左移不能到第一个元素之前,右移不能到最后一个元素之后 else if ( (direction === LEFT && position === 0) || (direction === RIGHT && position === items.length - 1) ) { return; } const item = items[position]; const newItems = items.filter(i => i.id !== id); newItems.splice(position + direction, 0, item); this.setState({ items: newItems }); }; render() { return <FruitList fruitList={this.state.items} onMove={this.handleMove} />; } } export default App;
2. 调整FruitList组件
把上下箭头换成左右箭头,同时修改方向常量,调整按钮的布局(比如让按钮横向排列):
import React from "react"; // 同步替换方向常量 const LEFT = -1; const RIGHT = 1; class FruitList extends React.Component { render() { const { fruitList, onMove } = this.props; return ( <div style={{ display: "flex", gap: "10px", padding: "10px" }}> {fruitList.map(item => ( <div key={item.id} style={{ backgroundColor: item.bgColor, padding: "10px", display: "flex", flexDirection: "column", alignItems: "center" }} > <div className="fruitsId">{item.id}</div> <div className="fruitsName">{item.name}</div> <div className="fruitsArrows" style={{ marginTop: "8px", display: "flex", gap: "5px" }}> {/* 左箭头图标 */} <a onClick={() => onMove(item.id, LEFT)} style={{ cursor: "pointer" }}>◀</a> {/* 右箭头图标 */} <a onClick={() => onMove(item.id, RIGHT)} style={{ cursor: "pointer" }}>▶</a> </div> </div> ))} </div> ); } } export default FruitList;
额外优化(可选)
如果你希望列表项是横向排列的,我在上面的代码里已经加了简单的flex布局样式,你可以根据自己的需求调整gap、padding这些样式参数,让界面更美观。
内容的提问来源于stack exchange,提问作者Neff
相关产品推荐
相关产品推荐

