javascript - Reactjs/Typescript 无法将项目数组作为属性传递给子项

标签 javascript arrays reactjs typescript properties

我的项目中有几个类,是使用 create-react-app 创建的,我想将对象数组传递给子元素,如下所示。

项目.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;

ItemsTable.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;

遗憾的是,在构建/编译过程中,我不断收到一条错误,指出 type '{ items: IItem[]; }' 无法分配给类型 'items: IItem[]'。请注意,与第一个实例相比,第二个实例中缺少大括号。

我认为 Typescript 或 React 显然是将数组粘贴到对象中,而不是像我期望的那样传递数组。

有人能弄清楚我在这里可能做错了什么吗?

最佳答案

您需要将 props 传递给 ItemTable,而不是直接传递 items

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

应该是

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

也可以缩写为

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

关于javascript - Reactjs/Typescript 无法将项目数组作为属性传递给子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805206/

相关文章:

php - 打印数组的偶数和(排序的)奇数

javascript - 在 React 中嵌套三个组件

javascript - 使用 JavaScript 从 html 复选框接收信息

javascript - 从另一个 CoffeeScript 文件访问变量?

javascript - .clone 不是函数

java - 如何在数组中同时调用抽象方法和接口(interface)方法?

javascript - 如何从父数组中过滤出子数组?

javascript - 在 Redux 表单子(monad)项中获取 Parent Prop

javascript - 如何使用 JS 将字符串替换为图像

javascript - 如何在 "return false"上设置超时?