Sobes.tech
Middle

Esercizio pratico: implementare un componente tabella in React + TypeScript con parametrizzazione tramite props (dati, colonne, gestore clic su riga onRowClick), che mostra un alert con l'identificatore della registrazione al clic su una riga.

sobes.tech AI

Risposta dell'AI

tsx import React from 'react';

type Column<T> = { key: keyof T; label: string; };

type TableProps<T extends { id: string | number }> = { data: T[]; columns: Column<T>[]; onRowClick: (id: T['id']) => void; };

function Table<T extends { id: string | number }>({ data, columns, onRowClick }: TableProps<T>) { return ( <table> <thead> <tr> {columns.map(col => ( <th key={String(col.key)}>{col.label}</th> ))} </tr> </thead> <tbody> {data.map(row => ( <tr key={String(row.id)} onClick={() => onRowClick(row.id)} style={{ cursor: 'pointer' }}> {columns.map(col => ( <td key={String(col.key)}>{String(row[col.key])}</td> ))} </tr> ))} </tbody> </table> ); }

// Пример использования:

// type User = { id: number; name: string; age: number }; // const users: User[] = [ // { id: 1, name: 'Иван', age: 30 }, // { id: 2, name: 'Мария', age: 25 }, // ]; // const columns = [ // { key: 'name', label: 'Имя' }, // { key: 'age', label: 'Возраст' }, // ]; // // <Table // data={users} // columns={columns} // onRowClick={(id) => alert(Вы кликнули по записи с id: ${id})} // />