Exercice pratique : implémenter un composant de tableau en React + TypeScript avec paramétrage via des props (données, colonnes, gestionnaire de clic sur la ligne onRowClick), qui affiche une alerte avec l'identifiant de l'enregistrement lors du clic sur une ligne.
sobes.tech IA
Réponse de l'IA
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})}
// />