react实现列表排序的方法:1、将整体设置成一个无序列表,并将子元素放置li内;2、在“Radio.Group”中进行Radio的移动;3、通过arrayMoveImmutable数组重新排序函数实现列表排序即可。
本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。
react 自定义拖拽排序列表
一、背景
最近在公司开发时,遇到需要自定表单,并且自定表单中的单选和复选选项需要用户可以自定义拖拽排序,经过一个星期的查阅各种资料和实践,写个总结!
二、实践
经过一系列的查询,发现React Sortable与array-move可以实现这一功能!
附上官网链接React Sortable Higher-order Components
对应git源码 https://www.php.cn/link/64bba6f0069347b04a9de74a54352890
因此借鉴官网案例开始我们的对应的需求开发!
要实现是需要三个主要组件。
1、SortableContainer 整体实现移动的容器
<SortableContainer onSortEnd={onSortEnd} useDragHandle> { radioList.map((item,index)=>{ return( <SortableItem key={`item-${item.id}`} index={index} item = {item} num={index} /> ) }) } </SortableContainer>
我们将整体设置成一个无序列表,将子元素放置li内,方便我们进行排序!
const SortableContainer = sortableContainer(({children}) => { return <ul>{children}</ul>;
onSortEnd 移动完毕后执行的函数
const onSortEnd = ({oldIndex, newIndex}) => { var arry1 = arrayMoveImmutable(radioList,oldIndex,newIndex) setRadioList(arry1); };
useDragHandle 移动的控件(焦点)---如果不需要可以不写
const DragHandle = sortableHandle(() => <UnorderedListOutline style = {{position:'absolute',right:'30px',top:'10px',display:isEdit == true ? '':'none'}}/>);
<br>
2、SortableItem 移动的对象
const SortableItem = sortableElement(({item,num}) => ( <li> <Radio key = {item.id} value = {item.value} style = {{width:'100%',position:'relative'}} > <Input style = {{border:'none',width:'96%'}} placeholder = {`选项${num+1}`} defaultValue={item.value} onBlur = {(e)=>{ item.value = e.target.value console.log(item.value); setRadioList([...radioList])}} readOnly = {isEdit == true ? '':'none'}></Input> <DragHandle /> <CloseCircleOutline onClick = {()=>{deleteRadio(item)}} style = {{position:'absolute',right:'10px',top:'10px',display:isEdit == true ? '':'none'}}/> </Radio> </li> ));
对象需要自己构建,我这边由于元素比较多,所以看起来比较复杂。
我们的需求是需要在Radio.Group中进行Radio的移动。所以将Radio封装到SortableItem中。
其中,接受的参数可以自定义,但需要和
中的名字对应起来,其中不能用index作为参数名。
3、arrayMoveImmutable 数组重新排序函数
const onSortEnd = ({oldIndex, newIndex}) => { var arry1 = arrayMoveImmutable(radioList,oldIndex,newIndex) setRadioList(arry1); };
arrayMoveImmutable函数接受3个参数,一个是操作的数组,一个是操作元素原本的index,一个是新的操作元素所放置的index。函数返回移动完毕的数组。
三、整体效果
因此,我们的操作步骤结束,整体代码。没有导入的包需要自行npm 安装!
import React, { useState,useEffect } from "react"; import { Input,Radio, Button,Space,Checkbox,Form } from "antd"; import { DeleteOutline, CloseCircleOutline,UnorderedListOutline } from 'antd-mobile-icons' import { Dialog, Toast, Divider } from 'antd-mobile' import { sortableContainer, sortableElement, sortableHandle, } from 'react-sortable-hoc'; import {arrayMoveImmutable} from 'array-move'; const RadioComponent = (props) => { const {onDelete,onListDate,componentIndex,setIsEdit,isEdit,componentTitle,componentDate,previewVisible} = props; const [radioList,setRadioList] = useState([]) const [remark, setRemark] = useState(false) const [required, setRequired] = useState(false) const [radioTitle, setRadioTitle] = useState('') const [id, setId] = useState(2) const [radioId, setRadioId] = useState(111211) useEffect(()=>{ if(componentDate !== undefined){ setRadioList(componentDate) }else{ setRadioList([{id:0,value:''},{id:1,value:''}]) } },[componentIndex]) useEffect(()=>{ if(isEdit === false && previewVisible === undefined){ onListDate(radioList,radioTitle,required,remark) } },[isEdit]) const onChange = (e) => { console.log(e.target.value); setRequired(e.target.checked) }; // 添加备注 const addRemark = ()=>{ setRemark(true) } // 删除备注 const deleteRemark = ()=>{ setRemark(false) } // 删除选项 const deleteRadio = (item)=>{ console.log(item); if(radioList.indexOf(item) > -1){ radioList.splice(radioList.indexOf(item),1) } setRadioList([...radioList]) } const SortableItem = sortableElement(({item,num}) => ( <li> <Radio key = {item.id} value = {item.value} style = {{width:'100%',position:'relative'}} > <Input style = {{border:'none',width:'96%'}} placeholder = {`选项${num+1}`} defaultValue={item.value} onBlur = {(e)=>{ item.value = e.target.value console.log(item.value); setRadioList([...radioList])}} readOnly = {isEdit == true ? '':'none'}></Input> <DragHandle /> <CloseCircleOutline onClick = {()=>{deleteRadio(item)}} style = {{position:'absolute',right:'10px',top:'10px',display:isEdit == true ? '':'none'}}/> </Radio> </li> )); const onSortEnd = ({oldIndex, newIndex}) => { var arry1 = arrayMoveImmutable(radioList,oldIndex,newIndex) setRadioList(arry1); }; const DragHandle = sortableHandle(() => <UnorderedListOutline style = {{position:'absolute',right:'30px',top:'10px',display:isEdit == true ? '':'none'}}/>); const SortableContainer = sortableContainer(({children}) => { return <ul>{children}</ul>; }); return(* {componentIndex} [单选] {setRadioTitle(e.target.value);}} readOnly = {isEdit == true ? '':'none'} >) } export default RadioComponent{ radioList.map((item,index)=>{ return( ) }) } 备注 |必填 { const result = await Dialog.confirm({ content: '是否确定删除该题目?', }) if (result) { Toast.show({ content: '点击了确认', position: 'bottom' }) onDelete(componentIndex) } else { Toast.show({ content: '点击了取消', position: 'bottom' }) } }} style={{float:'right',margin:'10px'}} />
<br>
推荐学习:《react视频教程》
以上是react怎么实现列表排序的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Dreamweaver Mac版
视觉化网页开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能