reactJs中JSON的网格视图格式

时间:2019-06-18 07:24:32

标签: javascript json reactjs user-interface

我有一个react组件,在其中我需要呈现从第3方API获取的JSON。 JSON类型

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]

我需要呈现在3列表中获取的JSON。

Red     Green     Blue
Cyan    Magenta   Yellow
Black

我能够以单列样式进行渲染,但是遇到多列问题。

有什么办法可以做到吗?

1 个答案:

答案 0 :(得分:1)

您应该像下面那样更新组件样式。

const data = [
  {
    color: "red",
    value: "#f00"
  },
  {
    color: "green",
    value: "#0f0"
  },
  {
    color: "blue",
    value: "#00f"
  },
  {
    color: "cyan",
    value: "#0ff"
  },
  {
    color: "magenta",
    value: "#f0f"
  },
  {
    color: "yellow",
    value: "#ff0"
  },
  {
    color: "black",
    value: "#000"
  }
];

class Hello extends React.Component {
  render() {
    return (
      <div style={{ display: "flex", flexWrap: "wrap" }}>
        {data.map(item => (
          <div style={{ flex: 1, flexBasis: "33%" }}>{item.color}</div>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<Hello />, document.getElementById("container"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="container"></div>