React开发:点击按钮实现列表元素逐次上下移位功能问题求助
功能实现修改点
- 给上下移动方法传入当前元素的索引,用于定位要交换位置的元素
- 补充边界判断,避免第一个元素上移、最后一个元素下移的异常操作
- 基于不可变原则更新数组,交换目标元素的位置
完整修改后的代码
const [inputList, setInputList] = useState([{ inputBox: '' }]); const handleInputChange = (e, index) => { const { name, value } = e.target; const list = [...inputList]; list[index][name] = value; setInputList(list); }; const handleRemoveClick = (index) => { const list = [...inputList]; list.splice(index, 1); setInputList(list); }; const handleAddClick = () => { setInputList([...inputList, { inputBox: '' }]); }; const upPosition = (index) => { // 顶部元素禁止上移 if (index === 0) return; const newList = [...inputList]; // 交换当前元素与上一位元素的位置 [newList[index], newList[index - 1]] = [newList[index - 1], newList[index]]; setInputList(newList); }; const downPosition = (index) => { // 底部元素禁止下移 if (index === inputList.length - 1) return; const newList = [...inputList]; // 交换当前元素与下一位元素的位置 [newList[index], newList[index + 1]] = [newList[index + 1], newList[index]]; setInputList(newList); }; return ( <div> <h3>Add Elements</h3> <button onClick={handleAddClick}>+</button> {inputList.map((x, i) => { return ( <div className='box inputBox' key={i}> <input name='inputBox' value={x.inputBox} onChange={(e) => handleInputChange(e, i)} /> <button onClick={() => upPosition(i)}> <i className='fas fa-long-arrow-alt-up'></i> </button> <button onClick={() => downPosition(i)}> <i className='fas fa-long-arrow-alt-down'></i> </button> <button className='mr10' onClick={() => handleRemoveClick(i)}> <i className='fas fa-times'></i> </button> </div> ); })} </div> );
修改后点击对应元素的上下箭头即可实现逐次移动,输入框内的内容会随元素同步移动,不会丢失。
内容的提问来源于stack exchange,提问作者Abubakar Oluyinka
相关产品推荐
相关产品推荐

