Close
Angular React Web Components Blazor
Premium

React Grid セル編集

React Grid の Ignite UI for React セル編集機能は、React Grid コンポーネント内の個々のセルのコンテンツの優れたデータ操作機能を提供し、React CRUD 操作用の強力な API を備えています。これはスプレッドシート、データ テーブル、データ グリッドなどのアプリの基本的な機能であり、ユーザーが特定のセル内のデータを追加、編集、更新できるようにします。 デフォルトでは、Ignite UI for React の Grid がセル編集に使用されます。また、デフォルトのセル編集テンプレートにより、列のデータ型 「Top of Form」 に基づいて異なるエディターが存在します。

さらに、データ更新アクション用の独自のカスタム テンプレートを定義したり、変更をコミット/破棄したりするためのデフォルトの動作をオーバーライドすることもできます。

React Grid セル編集と編集テンプレートの例

セルの編集

UI を介した編集

編集可能なセルがフォーカスされたときに以下のいずれかの方法で特定のセルを編集モードにすることができます。

  • ダブル クリック
  • シングル クリック - 以前選択したセルが編集モードで現在選択したセルが編集可能な場合のみ、シングル クリックで編集モードに入ります。以前選択したセルが編集モードではない場合、編集モードに入らずにシングル クリックでセルを選択します。
  • ENTER キーの押下
  • F2 キーの押下

変更をコミットしない場合も以下の方法で編集モードを終了できます。

  • Escape キーの押下;
  • ソート、フィルターリング、検索、非表示操作の実行時。

変更をコミットしない場合も以下の方法で編集モードを終了できます。

  • ENTER キーの押下
  • F2 キーの押下
  • TAB キーの押下
  • 他のセルをシングル クリック - IgrGrid で他のセルをクリックしたときに変更がサブミットされます。
  • その他の操作 (ページング、サイズ変更、ピン固定、移動など) は、編集モードを終了して変更を送信します。

セルは、垂直/水平方向へのスクロールや IgrGrid 以外をクリックした場合も編集モードのままです。セル編集と行編集両方で有効です。

API を介した編集

プライマリキーが定義されている場合のみ IgrGrid API でもセル値を変更することができます。

function updateCell() {
    grid1Ref.current.updateCell(newValue, rowID, 'ReorderLevel');
}

セルを更新するその他の方法として CellUpdate メソッドで直接更新する方法があります。

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);
}

セル編集テンプレート

デフォルトのセル編集テンプレートの詳細については、編集トピックを参照してください。

そして、テンプレートを index.ts ファイルのこの列に渡します。

<IgbColumn
    Field="Race"
    DataType="GridColumnDataType.String"
    InlineEditorTemplateScript="WebGridCellEditCellTemplate"
    Editable="true"
    Name="column1"
    @ref="column1">
</IgbColumn>

そして、テンプレートを index.ts ファイルのこの列に渡します。

<IgbColumn
    Field="Category"
    DataType="GridColumnDataType.String"
    InlineEditorTemplateScript="WebGridCellEditCellTemplate"
    Editable="true"
    Name="column1"
    @ref="column1">
</IgbColumn>

そして、テンプレートを index.ts ファイルのこの列に渡します。

Grid Excel スタイル編集

Excel スタイル編集を使用すると、Excel を使用する場合と同じようにセルをナビゲートし、すばやく編集できます。

このカスタム機能を実装するには、IgrGrid のイベントを使用します。最初にグリッドの keydown イベントにフックし、そこから 2 つの機能を実装できます。

const gridRef = useRef<IgrGrid>();
useEffect(() => {
    gridRef.current.addEventListener("keydown", handleKeyDown);
    return () => {
        gridRef.current.removeEventListener("keydown", handleKeyDown);
    };
}, []);
<IgrGrid ref={gridRef} autoGenerate={false} data= primaryKey="ProductID">
</IgrGrid>

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.

React の合成 onKeyDown イベントの代わりに、ネイティブ ブラウザーの keydown イベントを使用しています。セルが編集モードに入り、ENTER キーを押して次の行に移動すると、グリッドの編集機能によってセルの値が更新され、編集モードが閉じられます。その結果、編集に使用された入力要素は DOM から削除されます。React のイベント システムの最適化により、その時点で要素が React ツリー内に存在しなくなるため、onKeyDown 合成イベントはグリッドにバブルアップされません。したがって、期待される動作を確実にするには、ネイティブ イベント リスナーを使用する必要があります。

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;
        }
    }
}
  • 常時編集モード
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();
    });
}
  • ENTER/SHIFT + ENTER ナビゲーション
//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 スタイル編集のサンプル

上記のアプローチの主な利点は次のとおりです:

  • 常時編集モード: セルが選択されているときに入力すると、編集モードに入り、入力された値が既存の値を置き換えます。
  • ENTER/SHIFT + ENTER で移動する場合、データ以外の行はスキップされます。これにより、ユーザーは値をすばやく切り替えることができます。

CRUD 操作

CRUD 操作を実行した場合、filteringsortinggrouping などのパイプが再適用されるため、ビューが自動的に更新されることに注意してください。

IgrGrid は基本的な CRUD 操作のための簡易な API を提供します。

新しいレコードの追加

IgrGrid コンポーネントは、提供したデータをデータ ソースに追加する AddRow メソッドを公開します。

// Adding a new record
// Assuming we have a `getNewRecord` method returning the new row data.
const record = getNewRecord();
grid1Ref.current.addRow(record);

データを Grid で更新

Grid のデータ更新は、グリッドで PrimaryKey が定義されている場合のみ UpdateRowUpdateCell メソッドで行うことができます。セルと行の値またはそのいずれかを各 update メソッドで直接更新できます。

// 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);

Grid からデータを削除

DeleteRow メソッドは、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();

IgrGrid に関係なく、ボタンのクリックなどのユーザー インタラクションに関連付けできます。

編集イベントでのセル検証

IgrGrid の編集イベントを使用して、ユーザーが IgrGrid を操作する方法を変更できます。

この例では、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!");
        }
    }
}

Units On Order (注文済み) 列の下のセルに入力された値が使用可能量 (Units in Stock、在庫数 の値) よりも大きい場合、編集はキャンセルされ、ユーザーにキャンセルの警告が表示されます。

ここでは、2 つの列を検証しています。ユーザーが従業員の Age (年齢、18 歳未満) または Hire Date (雇用日、将来の日付) に無効な値を設定しようとすると、編集がキャンセルされ (値は送信されません)、エラー メッセージ付きのトースターが表示されます。

スタイル設定

事前定義されたテーマに加えて、利用可能な CSS プロパティを設定することでグリッドをさらにカスタマイズできます。 一部の色を変更したい場合は、最初にグリッドのクラスを設定する必要があります。

<IgrGrid className="grid"></IgrGrid>

Then set the related CSS properties for that class:

.grid {
    --ig-grid-edit-mode-color: #FFA500;
    --ig-grid-cell-active-border-color: #FFA500;
    --ig-grid-cell-editing-background: #add8e6;
}

スタイル設定の例

IgrGridIgnite UI for React テーマ ライブラリ を使用してセルのスタイルを設定できます。グリッドの theme は、ユーザーがグリッドのさまざまな側面をスタイル設定できる広範なプロパティを公開します。

API リファレンス

IgrGrid
IgrColumn
IgrDatePicker

パレットの定義