如何在React Js中映射二维数组

时间:2018-05-06 16:34:53

标签: reactjs

Projects.js

 constructor() {
  super();
  this.state = {
     projects: [] 
  }
}

componentWillMount() {
  this.setState({
     projects: [
        {
           link: '/',
           img: 'img.jpg',
           title: 'Title',
           date: 'Jul 2017',
           description: 'Description',
           icons: 
           [
              {
                 src: 'icon.svg',
                 content: 'Content'
              },
              {
                 src: 'icon2.svg',
                 content: 'Content 2'
           ]
        }
     ]
   });
  }

render() {
   return (
      <section className="projects">
         <ProjectsList projects={this.state.projects} />
      </section>
   );
  }
}

ProjectsList.js

let projectItems;

projectItems = this.props.projects.map(project => {
  return (
    <ProjectItem key={project.title} project={project}  />
  ) 
});

return (
   <div id="projectsList">
     {projectItems}
   </div>
)

我想创建一个项目卡,底部有一个图标列表。我可以映射项目数组,但图标不会起作用。任何人都知道如何在ReactJs中映射这个2d数组?谢谢!

3 个答案:

答案 0 :(得分:1)

再次使用地图:

projectItems = this.props.projects.map(project => {
  return (
    <div>
      <ProjectItem key={project.title} project={project}  />
      { 
        project.icons.map(i => <img key={i.src} src={i.src} alt="" />) 
      }
    </div>
  ) 
});

你当然可以在ProjectItem

内完成

答案 1 :(得分:0)

在ProjectItem组件中,您需要映射图标。您的ProjectItem组件看起来像

const ProjectItem = ({project}) => {
    return (
        <div className={'card'}>
            {/*content for link, img, title, description here */}
             {project.icons.map((icon, key) => <img src={icon.content} />)}
        </div>
    )
}

答案 2 :(得分:0)

array = [[null,null,null],[null,null,null]]

return (
<div> {array.map(x=> x.map(y=> <div>{....}</div> ))}</div>
)

将它再次映射到数组中将给出值