在React中将道具映射到数组

时间:2018-05-01 15:30:08

标签: javascript reactjs react-props

所以我想迭代一些传递给我的react组件的道具,并根据道具传递的链接数构建一组动态的html元素。下面的示例将只呈现第一个链接。

import React from "react";
import ReactDOM from "react-dom";

const Links = (props) => {
   return (
      <div>
        <p>{props.link.link1}</p>
      </div>
    )
  }

export default Links;

我无法确定如何映射传入的道具,以便为道具对象中的每个链接生成 p标记。链接从较大的json对象中拉出,并作为props传递给上面的组件。

"links": {
      "link1": "https://www.google.com",
      "link2": "https://www.google.com",
      "link3": "https://www.google.com",
      "link4": "https://www.google.com",
      "link5": "https://www.google.com",
      "link6": "https://www.google.com"
 }

我尝试过类似下面的内容,但却无法让它发挥作用。我需要基于反应组件类吗?并引入构造函数/ render方法来正确执行此操作?

const buildLinks = this.props.data.map(release => {
    render (
        /// p tags + props go here
    )
})

2 个答案:

答案 0 :(得分:2)

使用Object.keys()将对象转换为数组,并使用Array.map()创建JSX:

const props = {
  "links": {
    "link1": "https://www.google.com",
    "link2": "https://www.yahoo.com",
    "link3": "https://www.facebook.com",
    "link4": "https://www.twitter.com",
    "link5": "https://www.instagram.com",
    "link6": "https://www.gmail.com"
  }
};

const Links = ({ links }) => {
   return (
      <div>
        {
          Object.keys(links).map((link) => (
            <p key={link}>{ links[link] }</p>
          ))
        }
      </div>
    )
  }

ReactDOM.render(
  <Links {...props} />,
  demo
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>

答案 1 :(得分:1)

var link = {
  "links": {
    "link1": "https://www.google.com",
    "link2": "https://www.yahoo.com",
    "link3": "https://www.facebook.com",
    "link4": "https://www.twitter.com",
    "link5": "https://www.instagram.com",
    "link6": "https://www.gmail.com"
  }
}

var newlink = Object.values(link)

console.log(Object.values(newlink[0]))

然后你可以映射它们。如你所愿。