React Descripción general de la selección de cuadrícula
Con la función Ignite UI for React Select de React Grid, puede interactuar y manipular fácilmente los datos mediante simples interacciones con el ratón. Hay tres modos de selección disponibles:
- Selección de fila
- Selección de celda
- Column selection
With the rowSelection property, you can specify:
- Ninguno
- Soltero
- Selección múltiple
React Grid Selection Example
The sample below demonstrates three types of cell selection behaviors in the IgrGrid. Use the buttons below to enable each of the available selection modes.
React Grid Selection Options
The Ignite UI for React IgrGrid component provides three different selection modes - Row selection, Cell selection and Column selection. By default only Multi-cell selection mode is enabled in the IgrGrid. In order to change/enable selection mode you can use rowSelection, cellSelection or selectable properties.
React Grid Row Selection
Property rowSelection enables you to specify the following options:
None- Row selection would be disabled for theIgrGrid.Single- Selection of only one row within theIgrGridwould be available.Multiple- Multi-row selection would be available by using the row selectors, with a key combination like CTRL + click, or by pressing the space key once a cell is focused.
Vaya al tema Selección de filas para obtener más información.
React Grid Cell Selection
Property cellSelection enables you to specify the following options:
None- Cell selection would be disabled for theIgrGrid.Single- Selection of only one cell within theIgrGridwould be available.Multiple- Currently, this is the default state of the selection in theIgrGrid. Multi-cell selection is available by mouse dragging over the cells, after a left button mouse clicked continuously.
Vaya al tema Selección de celda para obtener más información.
React Grid Column Selection
The selectable property enables you to specify the following options for each IgrColumn. The corresponding column selection will be enabled or disabled if this property is set to true or false, respectively.
Esto lleva a las siguientes tres variaciones:
- Selección única: haga clic con el mouse sobre la celda de la columna.
- Selección de varias columnas: mantener presionado CTRL + mouse click sobre las celdas de la columna.
- Selección de columna de rango: mantener presionado SHIFT + mouse click selecciona todo lo que hay en el medio.
Vaya al tema Selección de columnas para obtener más información.
React Grid Context Menu
Using the ContextMenu event you can add a custom context menu to facilitate your work with IgrGrid. With a right click on the grid's body, the event emits the cell on which it is triggered. The context menu will operate with the emitted cell.
Si hay una selección multicelda, pondremos lógica, que comprobará si la celda seleccionada está en el área de selección multicelda. Si es así, también emitiremos los valores de las celdas seleccionadas.
Básicamente la función principal se verá así:
const rightClick = (event: IgrGridContextMenuEventArgs) => {
const eventArgs = event.detail;
eventArgs.event.preventDefault();
const node = eventArgs.cell.cellID;
const isCellWithinRange = gridRef.current
.getSelectedRanges()
.some((range: any) => {
if (
node.columnID >= range.columnStart &&
node.columnID <= range.columnEnd &&
node.rowIndex >= range.rowStart &&
node.rowIndex <= range.rowEnd
) {
return true;
}
return false;
});
setIsCellWithinRange(isCellWithinRange);
setClickedCell(eventArgs.cell);
openContextMenu(eventArgs.event.clientX, eventArgs.event.clientY);
};
El menú contextual tendrá las siguientes funciones:
- Copia el valor de la celda seleccionada.
- Copie el dataRow de la celda seleccionada.
- Si la celda seleccionada está dentro de un rango de selección de varias celdas, copie todos los datos seleccionados.
const copySelectedRowData = () => {
const selectedData = gridRef.current.getRowData(clickedCell.cellID.rowID);
copyData(selectedData);
closeContextMenu();
};
const copySelectedCellData = () => {
const selectedData = clickedCell.value;
copyData(selectedData);
closeContextMenu();
};
const copySelectedData = () => {
const selectedData = gridRef.current.getSelectedData(null, null);
copyData(selectedData);
closeContextMenu();
};
const copyData = (data: any[]) => {
const tempElement = document.createElement("input");
document.body.appendChild(tempElement);
tempElement.setAttribute("id", "temp_id");
(document.getElementById("temp_id") as HTMLInputElement).value =
JSON.stringify(data);
tempElement.select();
const dataStringified = JSON.stringify(data);
navigator.clipboard.writeText(dataStringified).catch((err) => {
console.error("Failed to copy: ", err);
});
document.body.removeChild(tempElement);
setSelectedData(dataStringified);
};
The IgrGrid will fetch the copied data and will paste it in a container element.
La plantilla que vamos a utilizar para combinar la grilla con el menú contextual:
<>
<div className="container sample">
<div className="wrapper" onClick={closeContextMenu}>
<IgrGrid
autoGenerate={false}
data={northWindData}
primaryKey="ProductID"
ref={gridRef}
onContextMenu={rightClick}
>
<IgrColumn field="ProductID" header="Product ID"></IgrColumn>
<IgrColumn field="ProductName" header="Product Name"></IgrColumn>
<IgrColumn
field="UnitsInStock"
header="Units In Stock"
dataType="number"
></IgrColumn>
<IgrColumn
field="UnitPrice"
header="Units Price"
dataType="number"
></IgrColumn>
<IgrColumn field="Discontinued" dataType="boolean"></IgrColumn>
<IgrColumn
field="OrderDate"
header="Order Date"
dataType="date"
></IgrColumn>
</IgrGrid>
<div className="selected-data-area">{selectedData}</div>
</div>
</div>
<div style={{ display: "none" }} className="contextmenu" ref={contextMenuRef}>
<span className="item" onClick={copySelectedCellData}>
<IgrIcon ref={iconRef} collection="material" name="content_copy"></IgrIcon>
Copy Cell Data
</span>
<span className="item" onClick={copySelectedRowData}>
<IgrIcon collection="material" name="content_copy"></IgrIcon>Copy Row Data
</span>
{isCellWithinRange && (
<span className="item" onClick={copySelectedData}>
<IgrIcon collection="material" name="content_copy"></IgrIcon>Copy Cells Data
</span>
)}
</div>
</>
Seleccione varias celdas y presione el botón derecho del mouse. Aparecerá el menú contextual y después de seleccionar Copiar datos de celdas, los datos seleccionados aparecerán en el cuadro vacío de la derecha.
El resultado es:
Known Issues and Limitations
When the grid has no primaryKey set and remote data scenarios are enabled (when paging, sorting, filtering, scrolling trigger requests to a remote server to retrieve the data to be displayed in the grid), a row will lose the following state after a data request completes:
- Selección de fila
- Fila Expandir/contraer
- Edición de filas
- Fijación de filas
API References
Additional Resources
- Selección de fila
- Selección de celda
- Paginación
- Filtración
- Clasificación
- resúmenes
- Columna en movimiento
- Virtualización y rendimiento
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.