React Grid 셀 편집
React Grid의 Ignite UI for React는 React Grid 구성 요소 내의 개별 셀의 내용에 대한 훌륭한 데이터 조작 기능을 제공하며 React CRUD 작업을 위한 강력한 API와 함께 제공됩니다. 스프레드시트, 데이터 테이블 및 데이터 그리드와 같은 앱에서 기본적인 기능으로, 사용자가 특정 셀 내에서 데이터를 추가, 편집 또는 업데이트할 수 있습니다. 기본적으로 Ignite UI for React의 Grid는 셀 편집에 사용됩니다. 그리고 기본 셀 편집 템플릿으로 인해 Top of Form의 열 데이터 유형에 따라 다른 편집기가 있습니다.
또한 데이터 업데이트 작업에 대한 사용자 정의 템플릿을 정의하고 변경 사항 커밋 및 삭제에 대한 기본 동작을 재정의할 수 있습니다.
React Grid Cell Editing and Edit Templates Example
셀 편집
Editing through UI
다음 방법 중 하나로 편집 가능한 셀에 초점이 맞춰지면 특정 셀에 대한 편집 모드로 들어갈 수 있습니다.
- 두 번 클릭하면;
- 한 번 클릭 시 - 이전에 선택한 셀이 편집 모드이고 현재 선택한 셀이 편집 가능한 경우에만 한 번 클릭하면 편집 모드로 들어갑니다. 이전에 선택한 셀이 편집 모드가 아닌 경우 한 번 클릭하면 편집 모드로 들어가지 않고 셀이 선택됩니다.
- 키 누름 ENTER 시;
- 키를 누르면 F2;
다음 방법 중 하나로 변경 사항을 커밋하지 않고 편집 모드를 종료할 수 있습니다.
- 키를 누를 때 Escape;
- 정렬, 필터링, 검색 및 숨기기 작업을 수행할 때;
다음 방법 중 하나로 편집 모드를 종료하고 변경 사항을 커밋 할 수 있습니다.
- 키 누름 ENTER 시;
- 키를 누르면 F2;
- 키 누름 TAB 시;
- 다른 셀로 한 번 클릭하면 - 다른
IgrGrid셀을 클릭하면 변경 사항이 제출됩니다. - 페이징, 크기 조정, 고정 또는 이동과 같은 작업을 수행하면 편집 모드가 종료되고 변경 사항이 제출됩니다.
[!Note] The cell remains in edit mode when you scroll vertically or horizontally or click outside the
IgrGrid. This is valid for both cell editing and row editing.
Editing through API
또한 기본 키가 정의되어 있을 때만 API를 통해IgrGrid 셀 값을 수정할 수 있습니다:
function updateCell() {
grid1Ref.current.updateCell(newValue, rowID, 'ReorderLevel');
}
셀을 업데이트하는 또 다른 방법은 다음과 같은 방법을Update 직접 사용하는Cell 것입니다:
function updateCell() {
const cell = grid1Ref.current.getCellByColumn(rowIndex, 'ReorderLevel');
// You can also get cell by rowID if primary key is defined
// cell = grid1Ref.current.getCellByKey(rowID, 'ReorderLevel');
cell.update(70);
}
Cell Editing Templates
일반 편집 항목에서 기본 셀 편집 템플릿에 대해 자세히 알아보고 확인할 수 있습니다.
셀에 적용될 사용자 정의 템플릿을 제공하려는 경우 해당 템플릿을 셀 자체나 헤더에 전달할 수 있습니다. 먼저 평소와 같이 열을 만듭니다.
<IgrColumn
field="race"
header="Race"
dataType="string"
editable={true}
inlineEditorTemplate={this.webGridCellEditCellTemplate}>
</IgrColumn>
index.ts 파일의 이 열에 템플릿을 전달합니다.
public webGridCellEditCellTemplate = (e: IgrCellTemplateContext) => {
let cellValues: any = [];
let uniqueValues: any = [];
const cell = e.cell;
const colIndex = cell.id.columnID;
const field: string = this.grid1.getColumnByVisibleIndex(colIndex).field;
let index = 0;
for (const i of this.roleplayDataStats as any) {
if (uniqueValues.indexOf(i[field]) === -1) {
cellValues.push(
<>
<IgrSelectItem
selected={e.cell.value == i[field]}
value={i[field]}
>
<div>{i[field]}</div>
</IgrSelectItem>
</>
);
uniqueValues.push(i[field]);
}
index++;
}
return (
<>
<IgrSelect
onChange={(x: any) => {
setTimeout(() => {
cell.editValue = x.target.value;
});
}}
>
{cellValues}
</IgrSelect>
</>
);
};
추가 참조를 위해 위의 작업 샘플을 여기에서 찾을 수 있습니다.
Grid Excel Style Editing
Excel 스타일 편집을 사용하면 사용자는 Excel을 사용하는 것처럼 셀을 탐색하고 신속하게 편집할 수 있습니다.
이 사용자 지정 기능을 구현하려면 이벤트IgrGrid를 활용함으로써 가능합니다. 먼저 그리드의 키다운 이벤트에 연결하고, 거기서 두 가지 기능을 구현할 수 있습니다:
const gridRef = useRef<IgrGrid>();
useEffect(() => {
gridRef.current.addEventListener("keydown", handleKeyDown);
return () => {
gridRef.current.removeEventListener("keydown", handleKeyDown);
};
}, []);
<IgrGrid ref={gridRef} autoGenerate={false} data={NwindData} primaryKey="ProductID">
</IgrGrid>
[!Note] We are using the native browser keydown event instead of React’s synthetic onKeyDown event. When a cell enters edit mode and the ENTER key is pressed to move to the next row, the grid’s editing feature updates the cell value and closes the edit mode. As a result, the input element used for editing is removed from the DOM. Due to React’s event system optimizations, the onKeyDown synthetic event does not bubble up to the grid because the element no longer exists in the React tree at that moment. Therefore, using the native event listener is necessary to ensure the expected behavior.
- 상수 편집 모드
function handleKeyDown(event: KeyBoardEvent) {
const code = event.code;
const grid = event.currentTarget as IgrGrid;
const activeElem = grid.selectedCells[0];
if ((event.code >= "Digit0" && event.code <= "Digit9") || (event.code >= "KeyA" && event.code <= "KeyZ")
|| (event.code >= "Numpad0" && event.code <= "Numpad9" && event.code !== "Enter" && event.code !== "NumpadEnter")) {
if (activeElem && !activeElem.editMode) {
activeElem.editMode = true;
activeElem.editValue = event.key;
} else if (activeElem && activeElem.editMode) {
event.preventDefault();
activeElem.editValue = activeElem.editValue + event.key;
}
}
}
- ENTER / SHIFT + ENTER 탐색
if (code === "Enter" || code === "NumpadEnter") {
const thisRow = activeElem.row.index;
const dataView = grid.dataView;
const nextRowIndex = getNextEditableRowIndex(thisRow, dataView, event.shiftKey);
grid.navigateTo(nextRowIndex, activeElem.column.visibleIndex, (obj: any) => {
obj.target.activate();
grid.endEdit(true);
grid.markForCheck();
});
}
다음 적격 지수를 찾는 주요 부분은 다음과 같습니다.
//first we check if the currently selected cell is the first or the last
if (currentRowIndex < 0 || (currentRowIndex === 0 && previous) || (currentRowIndex >= dataView.length - 1 && !previous)) {
return currentRowIndex;
}
// in case using shift + enter combination, we look for the first suitable cell going up the field
if (previous) {
return dataView.findLastIndex((rec, index) => index < currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
}
// or for the next one down the field
return dataView.findIndex((rec, index) => index > currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
자세한 내용은 전체 샘플을 확인하세요.
React Grid Excel 스타일 편집 샘플
위 접근 방식의 주요 이점은 다음과 같습니다.
- 지속적인 편집 모드: 셀이 선택된 동안 입력하면 입력된 값으로 즉시 편집 모드로 들어가 기존 값을 대체합니다.
- 데이터가 아닌 행은 / SHIFT + ENTER로 ENTER 탐색할 때 건너뜁니다. 이를 통해 사용자는 자신의 값을 빠르게 순환할 수 있습니다.
CRUD operations
[!Note] Please keep in mind that when you perform some CRUD operation all of the applied pipes like filtering, sorting and grouping will be re-applied and your view will be automatically updated.
기본IgrGrid CRUD 작업을 위한 직관적인 API를 제공합니다.
Adding a new record
IgrGrid이 컴포넌트는 제공된 데이터를 데이터 소스에 추가하는 메서드를addRow 노출합니다.
// Adding a new record
// Assuming we have a `getNewRecord` method returning the new row data.
const record = getNewRecord();
grid1Ref.current.addRow(record);
Updating data in the Grid
그리드에서 데이터를 업데이트하는 것은 다음과 같이 이루어집니다.updateRow 그리고updateCell 방법론이지만 그리드의 PrimaryKey가 정의될 때만. 셀이나 행 값을 해당 값을 직접 업데이트할 수도 있습니다 업데이트 방법.
// Updating the whole row
grid1Ref.current.updateRow(newData, this.selectedCell.cellID.rowID);
// Just a particular cell through the Grid API
grid1Ref.current.updateCell(newData, this.selectedCell.cellID.rowID, this.selectedCell.column.field);
// Directly using the cell `update` method
selectedCell.update(newData);
// Directly using the row `update` method
const row = grid1Ref.current.getRowByKey(rowID);
row.update(newData);
Deleting data from the Grid
메서드는 adeleteRow가 정의된 경우에만 지정된 행을 제거한다는 점을 기억primaryKey 해 주세요.
// Delete row through Grid API
grid1Ref.current.deleteRow(selectedCell.cellID.rowID);
// Delete row through row object
const row = grid1Ref.current.getRowByIndex(rowIndex);
row.delete();
Cell Validation on Edit Event
theIgrGrid의 편집 이벤트를 이용해 사용자가 theIgrGrid와 상호작용하는 방식을 변경할 수 있습니다.
이 예시에서는 이벤트에CellEdit 결합하여 입력된 데이터를 바탕으로 셀을 검증합니다. 새로운 셀 값이 미리 정의된 기준을 충족하지 못하면, 이벤트를 취소하여 데이터 소스에 도달하지 못하게 합니다.
가장 먼저 해야 할 일은 그리드의 이벤트에 바인딩하는 것입니다.
<IgrGrid onCellEdit={handleCellEdit}>
</IgrGrid>
CellEdit어떤 셀의 값이 커밋될 때면 방출됩니다. CellEdit 정의에서는 어떤 조치를 취하기 전에 특정 열을 반드시 확인해야 합니다:
function handleCellEdit(args: IgrGridEditEventArgs): void {
const column = args.detail.column;
if (column.field === 'UnitsOnOrder') {
const rowData = args.detail.rowData;
if (!rowData) {
return;
}
if (args.detail.newValue > rowData.UnitsInStock) {
args.detail.cancel = true;
alert("You cannot order more than the units in stock!");
}
}
}
주문 단위 열 아래의 셀에 입력된 값이 사용 가능한 금액(재고 단위 아래의 값)보다 큰 경우 편집이 취소되고 사용자에게 취소 알림이 표시됩니다.
위 검증IgrGrid 결과는 아래 데모에서 확인할 수 있습니다:
Styling
사전 정의된 테마 외에도 사용 가능한 CSS 속성 중 일부를 설정하여 그리드를 추가로 사용자 정의할 수 있습니다. 일부 색상을 변경하려면 먼저 그리드에 대한 클래스를 설정해야 합니다.
<IgrGrid className="grid"></IgrGrid>
그런 다음 해당 클래스에 대한 관련 CSS 속성을 설정합니다.
.grid {
--ig-grid-edit-mode-color: orange;
--ig-grid-cell-editing-background: lightblue;
}