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 で他のセルをクリックしたときに変更がサブミットされます。
    • その他の操作 (ページング、サイズ変更、ピン固定、移動など) は、編集モードを終了して変更を送信します。

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

    API を介した編集

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

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

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

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

    セル編集テンプレート

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

    セルに適用されるカスタム テンプレートを提供する場合は、そのテンプレートをセル自体またはそのヘッダーに渡すことができます。まず、通常どおりに列を作成します。

    <IgrColumn
        field="race"
        header="Race"
        dataType="String"
        editable="true"
        name="column1"
        id="column1">
    </IgrColumn>
    

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

    public webGridCellEditCellTemplate = (e: { dataContext: IgrCellTemplateContext; }) => {
        let cellValues: any = [];
        let uniqueValues: any = [];
        const cell = e.dataContext.cell;
        const colIndex = cell.id.columnID;
        const field: string = this.grid1.getColumnByVisibleIndex(colIndex).field;
        const key = field + "_" + cell.id.rowID;
        let index = 0;
        for (const i of this.roleplayDataStats as any) {
          if (uniqueValues.indexOf(i[field]) === -1) {
            cellValues.push(
              <>
                <IgrSelectItem
                  selected={e.dataContext.cell.value == i[field]}
                  value={i[field]}
                  key={key + "_" + index}
                >
                  <div key={key + "_" + index}>{i[field]}</div>
                </IgrSelectItem>
              </>
            );
            uniqueValues.push(i[field]);
          }
          index++;
        }
        return (
          <>
            <IgrSelect
              key={key}
              change={(x: any) => {
                setTimeout(() => {
                  cell.editValue = x.value;
                });
              }}
            >
              {cellValues}
            </IgrSelect>
          </>
        );
      };
    

    上記のサンプルは、こちらで参照できます。

    Grid Excel スタイル編集

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

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

    • 常時編集モード
    function keydownHandler(event) {
      const key = event.keyCode;
      const grid = grid1Ref.current;
      const activeElem = grid.navigation.activeNode;
    
      if ((key >= 48 && key <= 57) ||
          (key >= 65 && key <= 90) ||
          (key >= 97 && key <= 122)) {
            // Number or Alphabet upper case or Alphabet lower case
            const columnName = grid.getColumnByVisibleIndex(activeElem.column).field;
            const cell = grid.getCellByColumn(activeElem.row, columnName);
            if (cell && !grid.crudService.cellInEditMode) {
                grid.crudService.enterEditMode(cell);
                cell.editValue = event.key;
            }
        }
    }
    
    • Enter/Shift+Enter ナビゲーション
    if (key == 13) {
        let thisRow = activeElem.row;
        const column = activeElem.column;
        const rowInfo = grid.dataView;
    
        // to find the next eligible cell, we will use a custom method that will check the next suitable index
        let nextRow = getNextEditableRowIndex(thisRow, rowInfo, event.shiftKey);
    
        // and then we will navigate to it using the grid's built in method navigateTo
        grid1Ref.current.navigateTo(nextRow, column, (obj) => {
            obj.target.activate();
            grid1Ref.current.clearCellSelection();
        });
    }
    

    次の適格なインデックスを見つけるための重要な部分は以下のようになります。

    //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 操作

    [!Note] 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.del();
    

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

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

    この例では、CellEdit イベントにバインドすることにより、入力されたデータに基づいてセルを検証します。セルの新しい値が事前定義された基準を満たしていない場合、イベントをキャンセルすることでデータソースに到達しないようにします。

    最初に必要なことは、グリッドのイベントにバインドすることです。

    <IgrGrid cellEdit={handleCellEdit}>
    </IgrGrid>
    

    CellEdit は、セルのがコミットされる直前に発生します。CellEdit の定義では、アクションを実行する前に特定の列を確認する必要があります。

    function handleCellEdit(s: IgrGridBaseDirective, 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、在庫数 の値) よりも大きい場合、編集はキャンセルされ、ユーザーにキャンセルの警告が表示されます。

    以下は、上記の検証が IgrGrid に適用された結果のデモです。

    スタイル設定

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

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

    次に、そのクラスに関連する CSS プロパティを設定します。

    .grid {
        --ig-grid-edit-mode-color: orange;
        --ig-grid-cell-editing-background: lightblue;
    }
    

    スタイル設定の例

    API リファレンス

    その他のリソース