2017-09-25 122 views
0

所以我想在typescript,imagelist中創建一個反應組件,它顯示圖像,鏈接和數字的列表。使用TypeScript創建接受數組的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 
    } ] } 

我有一個儀表盤組件,它看起來像這樣

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組件I中得到以下消息。

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] [1]:https://medium.com/@iktakahiro/react-stateless-functional-component-with-typescript-ce5043466011中描述的SFC類型定義。

我改變了我的代碼,這

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> 

我是新來的打字稿,覺得我缺少一些關鍵的東西。有任何想法嗎?

+0

我相信,通過將數據輸入您使用的是'ImageList'這個錯誤造成 –

回答

2

該錯誤有點模糊,但問題是你的函數返回一個數組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> 
); 

(也被刪除了幾個多餘的收益報表)

相關問題