搜索
首页web前端js教程react怎么实现列表排序
react怎么实现列表排序Dec 27, 2022 am 09:59 AM
react

react实现列表排序的方法:1、将整体设置成一个无序列表,并将子元素放置li内;2、在“Radio.Group”中进行Radio的移动;3、通过arrayMoveImmutable数组重新排序函数实现列表排序即可。

react怎么实现列表排序

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react 自定义拖拽排序列表

一、背景

最近在公司开发时,遇到需要自定表单,并且自定表单中的单选和复选选项需要用户可以自定义拖拽排序,经过一个星期的查阅各种资料和实践,写个总结!

2102ea2051ac39aef11d138cb2805b8.jpg

二、实践

经过一系列的查询,发现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:&#39;absolute&#39;,right:&#39;30px&#39;,top:&#39;10px&#39;,display:isEdit == true ? &#39;&#39;:&#39;none&#39;}}/>);
<br>

2、SortableItem 移动的对象

  const SortableItem = sortableElement(({item,num}) => (
    <li>
      <Radio key = {item.id} value = {item.value} style = {{width:&#39;100%&#39;,position:&#39;relative&#39;}} >
      <Input style = {{border:&#39;none&#39;,width:&#39;96%&#39;}} 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中。

其中,接受的参数可以自定义,但需要和

4fe4be416c9bc08d25bd5714a3fea8d.jpg

中的名字对应起来,其中不能用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:&#39;100%&#39;,position:&#39;relative&#39;}} >
      <Input style = {{border:&#39;none&#39;,width:&#39;96%&#39;}} 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:&#39;absolute&#39;,right:&#39;30px&#39;,top:&#39;10px&#39;,display:isEdit == true ? &#39;&#39;:&#39;none&#39;}}/>);
  const SortableContainer = sortableContainer(({children}) => {
  return <ul>{children}</ul>;
});
    return(
      
        *           {componentIndex} [单选]         {setRadioTitle(e.target.value);}} readOnly = {isEdit == true ? '':'none'} >                                         {               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'}}  />         
        
      
      )    } export default RadioComponent
<br>

推荐学习:《react视频教程

以上是react怎么实现列表排序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
react中canvas的用法是什么react中canvas的用法是什么Apr 27, 2022 pm 03:12 PM

在react中,canvas用于绘制各种图表、动画等;可以利用“react-konva”插件使用canvas,该插件是一个canvas第三方库,用于使用React操作canvas绘制复杂的画布图形,并提供了元素的事件机制和拖放操作的支持。

react中antd和dva是什么意思react中antd和dva是什么意思Apr 21, 2022 pm 03:25 PM

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

React是双向数据流吗React是双向数据流吗Apr 21, 2022 am 11:18 AM

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

react中为什么使用nodereact中为什么使用nodeApr 21, 2022 am 10:34 AM

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

react是组件化开发吗react是组件化开发吗Apr 22, 2022 am 10:44 AM

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react和reactdom有什么区别react和reactdom有什么区别Apr 27, 2022 am 10:26 AM

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。

react中forceupdate的用法是什么react中forceupdate的用法是什么Apr 19, 2022 pm 12:03 PM

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react有没有双向绑定react有没有双向绑定Apr 21, 2022 am 10:24 AM

react中没有双向绑定;react的设计思想就是单向数据流,没有双向绑定的概念;react是view层,单项数据流只能由父组件通过props将数据传递给子组件,满足了view层渲染的要求并且更易测试与控制,所以在react中没有双向绑定。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

安全考试浏览器

安全考试浏览器

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