sortable " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

sortable涓嶳eact Hooks閰嶅悎浣跨敤

扬州沐宇科技
2024-06-27 12:07:20
sortable

sortable鏄竴涓敤浜庡疄鐜版嫋鎷芥帓搴忕殑搴擄紝鑰孯eact Hooks鏄疪eact鎻愪緵鐨勪竴绉嶆柊鐨勭壒鎬э紝鐢ㄤ簬鍦ㄥ嚱鏁扮粍浠朵腑浣跨敤鐘舵€佸拰鍏朵粬React鐗规€с€傝灏唖ortable涓嶳eact Hooks閰嶅悎浣跨敤锛屽彲浠ユ寜鐓т互涓嬫楠よ繘琛岋細

  1. 鍦≧eact椤圭洰涓畨瑁卻ortable搴擄細
npm install react-sortable-hoc
  1. 瀵煎叆sortable搴撳拰蹇呰鐨凴eact Hooks锛?/li>
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { useState } from 'react';
  1. 浣跨敤useState閽╁瓙鍒涘缓涓€涓姸鎬佹潵瀛樺偍鎺掑簭鍚庣殑鏁版嵁锛?/li>
const [items, setItems] = useState([1, 2, 3, 4, 5]);
  1. 鍒涘缓涓€涓猄ortableContainer锛屽苟鍦ㄥ叾涓槧灏勬帓搴忓悗鐨勬暟鎹細
const SortableList = SortableContainer(() => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </ul>
  );
});
  1. 鍒涘缓涓€涓猄ortableElement缁勪欢锛岀敤浜庢覆鏌撴瘡涓帓搴忛」锛?/li>
const SortableItem = SortableElement(({ value }) => {
  return <li>{value}</li>;
});
  1. 鍦⊿ortableList缁勪欢涓娇鐢╫nSortEnd鍥炶皟鍑芥暟鏉ュ鐞嗘嫋鎷芥帓搴忕粨鏉熷悗鐨勯€昏緫锛?/li>
const onSortEnd = ({ oldIndex, newIndex }) => {
  setItems(arrayMove(items, oldIndex, newIndex));
};
  1. 鏈€鍚庯紝鍦ㄧ粍浠朵腑娓叉煋SortableList缁勪欢锛屽苟灏唎nSortEnd鍥炶皟鍑芥暟浼犻€掔粰瀹冿細
return <SortableList items={items} onSortEnd={onSortEnd} />;

閫氳繃浠ヤ笂姝ラ锛屾偍鍙互灏唖ortable涓嶳eact Hooks閰嶅悎浣跨敤锛屽疄鐜版嫋鎷芥帓搴忓姛鑳藉苟鍦ㄥ嚱鏁扮粍浠朵腑绠$悊鐘舵€併€?/p>

扫码添加客服微信