>  기사  >  웹 프론트엔드  >  반응에서 목록 정렬을 구현하는 방법

반응에서 목록 정렬을 구현하는 방법

藏色散人
藏色散人원래의
2022-12-27 09:59:463001검색

반응에서 목록 정렬을 구현하는 방법: 1. 전체를 순서가 없는 목록으로 설정하고 하위 요소를 li에 배치합니다. 2. "Radio.Group"에서 라디오를 이동합니다. 3. arrayMoveImmutable 배열을 통해 함수를 재정렬합니다. 정렬.

반응에서 목록 정렬을 구현하는 방법

이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 18.0.0, Dell G3 컴퓨터.

react custom 드래그 앤 드롭 정렬 목록

1. Background

최근 회사에서 개발을 하다가 폼을 커스터마이징해야 할 필요성을 느꼈는데, 커스터마이징 폼의 라디오와 체크 옵션도 같이 해줘야 합니다. 사용자 정의 드래그 앤 드롭 정렬을 정의하세요. 일주일 동안 다양한 자료와 실습을 검토한 후 요약을 작성하세요!

반응에서 목록 정렬을 구현하는 방법

2. 연습

몇번의 쿼리 끝에 React Sortable과 array-move가 이 기능을 구현할 수 있다는 것을 알았습니다!

첨부된 공식 웹사이트 링크입니다React Sortable Higher-order Components

해당 git 소스 코드https://www.php.cn/link/64bba6f0069347b04a9de74a54352890

그래서 시작합니다 우리의 서신은 공식 홈페이지 케이스 요구사항 개발 !

구현하려면 세 가지 주요 구성 요소가 필요합니다.

1. SortableContainer 움직임을 전체적으로 구현하는 컨테이너

<sortablecontainer>
    {
     radioList.map((item,index)=>{
         return(
             <sortableitem></sortableitem>
            )
        })
    }
</sortablecontainer>

전체를 정렬되지 않은 목록으로 설정하고 정렬을 용이하게 하기 위해 하위 요소를 li에 배치합니다!

  const SortableContainer = sortableContainer(({children}) => {
  return 
    {children}
;

onSortEnd 이동이 완료된 후 실행되는 함수

 const onSortEnd = ({oldIndex, newIndex}) => {
    var arry1 = arrayMoveImmutable(radioList,oldIndex,newIndex)
    setRadioList(arry1);
  };

useDragHandle 이동 컨트롤(포커스) --- 필요하지 않으면 작성할 필요가 없습니다

  const DragHandle = sortableHandle(() => <unorderedlistoutline></unorderedlistoutline>);
<br>

2.

  const SortableItem = sortableElement(({item,num}) => (
    
  •              {         item.value = e.target.value         console.log(item.value);         setRadioList([...radioList])}}         readOnly = {isEdit == true ? '':'none'}>                {deleteRadio(item)}} style = {{position:'absolute',right:'10px',top:'10px',display:isEdit == true ? '':'none'}}/>          
  •   ));

    객체를 직접 구성해야 하는데, 여기에 요소가 더 많아져서 더 복잡해 보입니다.

    우리의 요구 사항은 Radio.Group에서 라디오를 이동하는 것입니다. 따라서 Radio를 SortableItem으로 캡슐화합니다.

    그 중 허용되는 매개변수는 사용자 정의가 가능하지만,

    반응에서 목록 정렬을 구현하는 방법

    에 있는 이름과 일치해야 하며, index는 매개변수 이름으로 사용할 수 없습니다.

    3. arrayMoveImmutable 배열 재정렬 함수

     const onSortEnd = ({oldIndex, newIndex}) => {
        var arry1 = arrayMoveImmutable(radioList,oldIndex,newIndex)
        setRadioList(arry1);
      };

    arrayMoveImmutable 함수는 3개의 매개변수를 받습니다. 하나는 연산의 배열이고, 하나는 연산 요소의 원래 인덱스이고, 다른 하나는 새 연산 요소가 배치되는 인덱스입니다. 이 함수는 이동된 배열을 반환합니다.

    3. 전반적인 효과

    이제 전체 코드 작업 단계는 끝났습니다. 가져오지 않은 패키지는 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}) => (
        
  •              {         item.value = e.target.value         console.log(item.value);         setRadioList([...radioList])}}         readOnly = {isEdit == true ? '':'none'}>                {deleteRadio(item)}} style = {{position:'absolute',right:'10px',top:'10px',display:isEdit == true ? '':'none'}}/>          
  •   ));   const onSortEnd = ({oldIndex, newIndex}) => {     var arry1 = arrayMoveImmutable(radioList,oldIndex,newIndex)     setRadioList(arry1);   };    const DragHandle = sortableHandle(() => <unorderedlistoutline></unorderedlistoutline>);   const SortableContainer = sortableContainer(({children}) => {   return 
      {children}
    ; });     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 비디오 튜토리얼"

    위 내용은 반응에서 목록 정렬을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.