Temă practică: implementați un component de tabel în React + TypeScript cu parametrizare prin props (date, coloane, handler de clic pe rând onRowClick), care la clic pe un rând afișează un alert cu identificatorul înregistrării.
sobes.tech AI
Răspuns de la 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})}
// />