如何在React中渲染一组Array对象和图像?

时间:2019-10-24 18:06:43

标签: arrays reactjs object

这是ModuleCardData.js

  {
    name: 'Smart Attendance',
    summary: 'Keep parents updated with live Attendance and monthly reports',
    image: '{Attendance}',
  },
  {
    name: 'Parents Communication Module',
    summary:
      'Chat with parents anytime, anywhere. Disable chat when you are busy.',
    image: '{Communication}',
  },
  {
    name: 'Class Management',
    summary: 'Forget tons of paperwork and manage your institute completely.',
    image: '{Class}',
  },
  {
    name: 'Fee Records',
    summary:
      'Automatic reminders and recepits of installments for student due fees.',
    image: '{Fee}',
  },
  {
    name: 'Insightful student reports.',
    summary: 'Personalized reports for all your students.',
    image: '{Stats}',
  },
  {
    name: 'Online Tests',
    summary:
      'Conduct your online tests powered with automatic checking and solution.',
    image: '{Test}',
  },
];

和我的ModuleCards.js文件。

import PropTypes from 'prop-types';
import './ModuleCards.scss';

//Img import.

import Attendance from '../Common/assets/images/smartattendance.svg';
import Communication from '../Common/assets/images/parents.svg';
import Test from '../Common/assets/images/test1.svg';
import Stats from '../Common/assets/images/reports.svg';
import Class from '../Common/assets/images/classmgmt.svg';
import Fee from '../Common/assets/images/fee.svg';

//Data import

import card from '../Common/data/ModuleCardsData.js';

class ModuleCards extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const cardData = { ...this.props.cardData };
    return (
      <div className="module-card">
        <img src={this.cardData.image} />
        <h3>{this.cardData.name}</h3>
        <p>{this.cardData.summary}</p>
      </div>
    );
  }
}

ModuleCards.propTypes = {};
export default ModuleCards;

如何从ModuleCardData文件正确渲染阵列?

我尝试了许多解决方案,例如处理道具等。 尤其是那些图像,是渲染这些图像的正确方法还是我应该使用另一种方法?

1 个答案:

答案 0 :(得分:1)

首先,您应该像这样从ModuleCardData.js导出数组

const myArrayCardData = [{
    name: 'Smart Attendance',
    summary: 'Keep parents updated with live Attendance and monthly reports',
    image: '{Attendance}',
  },
  {
    name: 'Parents Communication Module',
    summary:
      'Chat with parents anytime, anywhere. Disable chat when you are busy.',
    image: '{Communication}',
  }]

export default myArrayCardData;

然后,在您的反应文件中,您可以执行类似的操作

import cardData from './ModuleCardData';

,然后在您的渲染方法中,执行以下操作:

  render() {
    return cardData.map(card => {
      return (<div className="module-card">
        <img src={card.image} />
        <h3>{card.name}</h3>
        <p>{card.summary}</p>
      </div>)
    })
  }