我的项目中有几个类,是使用 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/