使用TypeScript创建一个接受数组的React无状态功能组件

时间:2017-09-25 14:54:42

标签: reactjs typescript

所以我想在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;

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.

我不确定此错误消息的含义。我的第一个想法是我需要使用[这里] [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>

我是打字稿的新手,觉得我错过了一些关键的东西。有任何想法吗?

1 个答案:

答案 0 :(得分:8)

错误有点模糊,但问题是你的函数返回一个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>
);

(还删除了一些冗余的返回语句)

相关问题