Búsqueda de sitios web

javascript - Reactjs/Typescript no puede pasar un arreglo de elementos como propiedad a un componente hijo


Tengo varias clases en un proyecto, creado con create-react-app, y quiero pasar un arreglo de objetos a elementos hijos, como se muestra a continuación.

Items.tsx

import * as React from 'react';
import ItemTable from './ItemTable';
import { IItem } from './ItemRow';

class Items extends React.Component {
    private items = IItem[];
    componentWillMount() {
      // connect to backend service and retrieve all Items
      items = get_items();
    }

    render() {
      return (
        <ItemTable items={this.items} />
      );
    }
}

export default Items;

TablaDeObjetos.tsx

import * as React from 'react';
import { Table } from 'reactstrap';
import ItemRow from './ItemRow';

let ItemTable = (items: IItem[]) => (
  <Table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Description</th>
        <th>Website</th>
      </tr>
    </thead>
    <tbody>
        {items.map(item => (
          <ItemRow item={item} />
        ))}
    </tbody>
  </Table>
);

export default ItemTable;

ItemRow.tsx

import * as React from 'react';

export interface IItem {
  name: string;
  description: string;
  website: string;
}

let ItemRow = (item: IItem) => (
  <tr>
    <td>{item.name}</td>
    <td>{item.description}</td>
    <td>{item.website}</td>
  </tr>
);

export default ItemRow;

Lamentablemente, durante la construcción/compilación sigo recibiendo un error que indica que el tipo '{ items: IItem[]; }' no se puede asignar al tipo 'items: IItem[]'. Nótese la ausencia de llaves en la segunda instancia en comparación con la primera.

Ya sea Typescript o React, supongo que Typescript, aparentemente está metiendo el array en un objeto en lugar de pasar el array como yo esperaba.

¿Alguien puede averiguar qué podría estar haciendo mal aquí?

Respuesta #1

Necesitas pasar props a tu ItemTable, no los items directamente

let ItemTable = (items: IItem[]) => (

Debería ser

let ItemTable = (props: {items: IItem[]}) => (
  const {items} = props;

Lo cual también se puede abreviar como

let ItemTable = ({items}: {items: IItem[]}) => (

Artículos relacionados