【发布时间】:2018-03-06 14:27:17
【问题描述】:
所以我想在 typescript、imagelist 中创建一个反应组件,它显示图像、链接和数字的列表。
我的 json 看起来像这样
{ "_id": "59c8ead6411f1e56f498a71b", "images": [
{
"post_url": "http://www.Facebook.com/974",
"image_url": "http://placehold.it/32x32",
"count": 887
},
{
"post_url": "http://www.Facebook.com/711",
"image_url": "http://placehold.it/32x32",
"count": 749
} ] }
我有一个看起来像这样的仪表板组件
import * as React from 'react';
const fakeData = require('./fake_data.json');
import ImageList from './ImageList';
export default class Dashboard extends React.Component { render() {
return (
<div>
<ImageList data={fakeData.images} />
</div>
); } }
我尝试如下定义我的 imagelist 组件
import * as React from 'react';
interface ImageListValue {
post_url: string;
image_url: string;
count: number;
}
interface ImageListProps {
data: ImageListValue[];
}
const ImageList = ({ data }: ImageListProps) => {
return data.map(item => {
return (
<div key={item.post_url}>
<a href={item.post_url}>{item.post_url}</a>
<img src={item.image_url} />
<h1>item.count</h1>
</div>
);
});
};
export default ImageList;
在 ImageList 组件中 linter 显示没有问题,但在 Dashboard 组件中我收到以下消息。
JSX element type 'Element[]' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Element[]'.
[ts] JSX element class does not support attributes because it does not have a 'props' property.
我不确定此错误消息的含义。我的第一个想法是我需要使用 [此处][1] 所述的 SFC 类型定义 [1]:https://medium.com/@iktakahiro/react-stateless-functional-component-with-typescript-ce5043466011。
我把代码改成了这个
const ImageList: React.SFC<ImageListProps> = ({data}) => {
return data.map(item => {
return (
<div key={item.post_url}>
<a href={item.post_url}>{item.post_url}</a>
<img src={item.image_url} />
<h1>item.count</h1>
</div>
);
});
};
又收到一个错误
[ts]
Type '({ data }: ImageListProps & { children?: ReactNode; }) => Element[]' is not assignable to type 'StatelessComponent<ImageListProps>'.
Type 'Element[]' is not assignable to type 'ReactElement<any> | null'.
Type 'Element[]' is not assignable to type 'ReactElement<any>'.
Property 'type' is missing in type 'Element[]'.
const ImageList: React.StatelessComponent<ImageListProps>
我是 typescript 的新手,感觉我错过了一些关键的东西。有任何想法吗?
【问题讨论】:
-
我相信这个错误是由您用于
ImageList的数据类型引起的
标签: reactjs typescript