use*_*889 4 typescript reactjs
所以我想在typescript,imagelist中创建一个react组件,它显示一个图像,链接和数字列表.
我的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
} ] }
Run Code Online (Sandbox Code Playgroud)
我有一个看起来像这样的仪表板组件
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>
); } }
Run Code Online (Sandbox Code Playgroud)
我试图定义我的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;
Run Code Online (Sandbox Code Playgroud)
linter在ImageList组件中没有显示任何问题,但在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.
Run Code Online (Sandbox Code Playgroud)
我不确定这个错误信息是什么意思.我的第一个想法是我需要使用[here] [1] [1]中描述的SFC类型定义: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>
);
});
};
Run Code Online (Sandbox Code Playgroud)
并收到另一个错误
[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>
Run Code Online (Sandbox Code Playgroud)
我是打字稿的新手,觉得我错过了一些关键的东西.有任何想法吗?
错误有点模糊,但问题是你的函数返回的是一个数组ReactElement而不是一个数组(在反应16中将允许返回一个数组).如果你将它包装在父级中div它应该工作:
const ImageList : React.SFC<ImageListProps> = ({data}) => (
<div>
{ data.map(item => (
<div key={item.post_url}>
<a href={item.post_url}>{item.post_url}</a>
<img src={item.image_url} />
<h1>item.count</h1>
</div>
))}
</div>
);
Run Code Online (Sandbox Code Playgroud)
(还删除了一些冗余的返回语句)
| 归档时间: |
|
| 查看次数: |
2204 次 |
| 最近记录: |