Arrastre de filas en la cuadrícula de árbol React
La función de arrastre de filas Ignite UI for React en React Tree Grid es fácilmente configurable y se utiliza para reorganizar filas dentro de la cuadrícula arrastrándolas y soltando a una nueva posición con el ratón. Se inicializa en el componente raízIgrTreeGrid y es configurable mediante larowDraggable entrada.
React Tree Grid Row Drag Example
Configuration
Para activar el arrastre de filas para tu,IgrTreeGrid solo tienes que poner las cuadrículasrowDraggable en true. Una vez habilitada esta opción, se mostrará una fila para arrastrar una fila. Esta manilla puede usarse para iniciar el arrastre de hilera. Hacer clic en el mando de arrastrar y mover el cursor mientras mantienes pulsado el botón hará que el evento deRowDragStart la cuadrícula se active. Soltar el clic en cualquier momento haráRowDragEnd que el evento se active.
<IgrTreeGrid rowDraggable={true}>
</IgrTreeGrid>
Templating the Drag Icon
El icono del mango de arrastrar puede plantarse usando las dedragIndicatorIconTemplate la cuadrícula. En el ejemplo que estamos construyendo, cambiemos el icono del predeterminado (drag_indicator) a drag_handle.
const dragIndicatorIconTemplate = (ctx: IgrGridEmptyTemplateContext) => {
return (
<>
<IgrIcon name="drag_handle" collection="material" />
</>
);
}
<IgrTreeGrid rowDraggable={true} dragIndicatorIconTemplate={dragIndicatorIconTemplate}>
</IgrTreeGrid>
Application Demo
Row Reordering Demo
Con la ayuda de los eventos de arrastre de filas de la cuadrícula, puede crear una cuadrícula que le permita reordenar las filas arrastrándolas.
<IgrTreeGrid rowDraggable={true} primaryKey="ID" onRowDragStart={webTreeGridReorderRowStartHandler} onRowDragEnd={webTreeGridReorderRowStartHandler}>
</IgrTreeGrid>
[!Note] Make sure that there is a
primaryKeyspecified for the grid! The logic needs an unique identifier for the rows so they can be properly reordered.
Una vezrowDraggable activado y definida una zona de caída, necesitas implementar un manejador sencillo para el evento de caída. Cuando se arrastra una fila, comprueba lo siguiente:
- ¿Se amplía la fila? Si es así, colapsarlo.
- ¿Se dejó caer la fila dentro de la cuadrícula?
- Si es así, ¿en qué otra fila se dejó caer la fila arrastrada?
- Una vez que hayas encontrado la fila objetivo, intercambia los registros en el
dataarray - ¿Se seleccionó inicialmente la fila? Si es así, márquelo como seleccionado.
A continuación, puedes ver esto implementado:
const webTreeGridReorderRowStartHandler = (args: IgrRowDragStartEventArgs) => {
const draggedRow = args.detail.dragData;
if (draggedRow.expanded) {
draggedRow.expanded = false;
}
}
const webTreeGridReorderRowHandler = (args: IgrRowDragEndEventArgs): void => {
const ghostElement = args.detail.dragDirective.ghostElement;
const dragElementPos = ghostElement.getBoundingClientRect();
const rows = Array.prototype.slice.call(document.getElementsByTagName("igx-tree-grid-row"));
const currRowIndex = getCurrentRowIndex(rows,
{ x: dragElementPos.x, y: dragElementPos.y });
if (currRowIndex === -1) { return; }
const draggedRow = args.detail.dragData.data;
const childRows = findChildRows(treeGridRef.current.data, draggedRow);
//remove the row that was dragged and place it onto its new location
treeGridRef.current.deleteRow(args.detail.dragData.key);
treeGridRef.current.data.splice(currRowIndex, 0, args.detail.dragData.data);
// reinsert the child rows
childRows.reverse().forEach(childRow => {
treeGridRef.current.data.splice(currRowIndex + 1, 0, childRow);
});
}
const findChildRows = (rows: any[], parent: any): any[] => {
const childRows: any[] = [];
rows.forEach(row => {
if (row.ParentID === parent.ID) {
childRows.push(row);
// Recursively find children of current row
const grandchildren = findChildRows(rows, row);
childRows.push(...grandchildren);
}
});
return childRows;
}
const getCurrentRowIndex = (rowList: any[], cursorPosition: any) => {
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;
}
¡Con estos sencillos pasos, ha configurado una cuadrícula que permite reordenar filas mediante arrastrar y soltar! Puede ver el código anterior en acción en la siguiente demostración.
Observe que también tenemos habilitada la selección de filas y conservamos la selección al soltar la fila arrastrada.
Limitations
Actualmente, no se conocen limitaciones para elrowDraggable.
API References
rowDraggableRowDragStartRowDragEndIgrTreeGrid
Additional Resources
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.