Praktiska uzdevuma: īstenot React + TypeScript komponentu ar tabulas ar parametrizāciju caur props (dati, kolonnas, onRowClick klikšķa apstrādātājs), kas noklikšķinot uz rindas parāda alert ar ieraksta identifikatoru.
sobes.tech AI
Atbilde no 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})}
// />