reactjs连续添加多张卡

时间:2018-05-16 23:52:06

标签: reactjs semantic-ui-react

您好我想知道如何连续添加多张卡(即4或5)。现在我只有一张卡片显示。

enter image description here

import React,{Component} from 'react';
import { Grid, Card, Icon, Image , Button} from 'semantic-ui-react'


export default class Class extends Component {

  constructor(props){
    super(props);
    this.state = {
      news:[],
    };
  }

componentDidMount() {

 const  url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=d5cf45043cd34b59b432df10e3cef274';


  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      this.setState({
        news: data.articles
      })
      console.log(data);
    })
    .catch((error)=>{
      console.log('error while trying to retrieve data')
    })
}

renderItems(){
  const src = 'https://placeimg.com/640/480/arch'
  return this.state.news.map((item) =>(
    <Card.Group>
      <Card
        image={src}
        header='Elliot Baker'
        meta='Friend'
        description='Elliot is a sound engineer living in Nashville who enjoys playing guitar and hanging with his cat.'
      />
    </Card.Group>

  ));
}


    render() {
        return (
          <Grid.Row>
            {this.renderItems()}
          </Grid.Row>
        );
    }
}

2 个答案:

答案 0 :(得分:1)

不是在组内部渲染单独的卡,而是渲染多个组,其中只有一张卡。如果您更新renderItems()方法,它将有效。使用map的Array方法,我们现在可以在名为card的变量中访问您所在州的每个项目的所有数据:

renderItems = () => {

  return (
    <Card.Group> 
      {this.state.news.map((card) => (
        <Card
          key={card.id} // Make sure you use a unique key identifier for React
          image={card.imageUrl} // This is the url of the image for the current object inside this.state.news.YOUR_CURRENT_OBJECT
          header={card.title}
          meta={card.type}
          description={card.description}
        />
      )}
    </Card.Group>
  )
}

答案 1 :(得分:0)

请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

renderItems(){
  return this.state.news.map((item) =>(
    <Card.Group>
      <Card
        image={item.urlToImage}
        header={item.author}
        meta={item.url}
        description={item.description}
      />
    </Card.Group>
  ));
}