React Grid の行ドラッグ
React Grid の Ignite UI for React 行ドラッグ機能は簡単に構成でき、マウスを使用して行を新しい位置にドラッグ アンド ドロップすることで、グリッド内の行を再配置するために使用されます。これはルートの IgrGrid コンポーネントで初期化され、rowDraggable 入力を介して構成できます。
React Grid 行ドラッグの例
構成
IgrGrid の行ドラッグを有効にするには、グリッドの rowDraggable を true に設定します。これが有効になると、行ドラッグ ハンドルが各行に表示されます。このハンドルは行ドラッグを開始するために使用できます。ドラッグ ハンドルをクリックしてボタンを押しながらカーソルを動かすと、グリッドの RowDragStart イベントが発生します。クリックをリリースすると、RowDragEnd イベントが発生します。
<IgrGrid rowDraggable={true}>
</IgrGrid>
ドラッグ アイコンのテンプレート化
ドラッグ ハンドル アイコンは、グリッドの dragIndicatorIconTemplate を使用してテンプレート化できます。作成している例で、アイコンをデフォルトのもの (drag_indicator) から drag_handle に変更します。
const dragIndicatorIconTemplate = (ctx: IgrGridEmptyTemplateContext) => {
return (
<>
<IgrIcon name="drag_handle" collection="material" />
</>
);
}
<IgrGrid rowDraggable={true} dragIndicatorIconTemplate={dragIndicatorIconTemplate}>
</IgrGrid>
新しいアイコン テンプレートの設定後、DragIcon enum の DEFAULT アイコンも調整する必要があるため、ChangeIcon メソッドによって適切に変更されます。
enum DragIcon {
DEFAULT = "drag_handle",
}
アプリケーション デモ
行の並べ替えデモ
グリッドの行ドラッグ イベントを使用して、ドラッグよる行の並べ替えるが可能なグリッドを作成できます。
<IgrGrid rowDraggable={true} primaryKey="ID" onRowDragEnd={webGridReorderRowHandler}>
</IgrGrid>
[!Note] グリッドに
primaryKeyが指定されていることを確認してください。ロジックが行を適切に並べ替えられるように、行には一意の識別子が必要です。
rowDraggable が有効になり、ドロップ エリアが定義されたら、ドロップ イベントの単純なハンドラーを実装する必要があります。行をドラッグするときは、以下を確認してください:
- 行はグリッド内にドロップされましたか?
- そうであれば、ドラッグされた行が他のどの行にドロップされましたか?
- ターゲット行が見つかれば、
data配列内のレコードの位置を入れ替えます。
以下では、上記の実装を示します。
const webGridReorderRowHandler = (args: IgrRowDragEndEventArgs): void => {
const ghostElement = args.detail.dragDirective.ghostElement;
const dragElementPos = ghostElement.getBoundingClientRect();
const rows = Array.prototype.slice.call(document.getElementsByTagName("igx-grid-row"));
const currRowIndex = getCurrentRowIndex(rows,
{ x: dragElementPos.x, y: dragElementPos.y });
if (currRowIndex === -1) { return; }
// remove the row that was dragged and place it onto its new location
gridRef.current.deleteRow(args.detail.dragData.key);
gridRef.current.data.splice(currRowIndex, 0, args.detail.dragData.data);
}
const getCurrentRowIndex = (rowList: any[], cursorPosition) => {
for (const row of rowList) {
const rowRect = row.getBoundingClientRect();
if (cursorPosition.y > rowRect.top + window.scrollY && cursorPosition.y < rowRect.bottom + window.scrollY &&
cursorPosition.x > rowRect.left + window.scrollX && cursorPosition.x < rowRect.right + window.scrollX) {
// return the index of the targeted row
return parseInt(row.attributes["data-rowindex"].value);
}
}
return -1;
}
これらの簡単な手順で、ドラッグ/ドロップで行を並べ替えることができるグリッドを構成しました! 次のデモで、上記コードの動作を確認できます。
ドラッグ アイコンを押下しながら、グリッド内で好きな場所に行を移動できます。
制限
現在、rowDraggable に既知の制限はありません。
API リファレンス
rowDraggableRowDragStartRowDragEndIgrGrid
その他のリソース
コミュニティに参加して新しいアイデアをご提案ください。