简体   繁体   English

如何在 React 中基于 JSON 渲染 HTML 元素?

[英]how to render HTML elements based on JSON in React?

I am trying to render some html elements based on JSON data.我正在尝试根据 JSON 数据渲染一些 html 元素。 I have a React class which takes these objects and produces a string list of divs;我有一个 React class 它接受这些对象并生成一个字符串列表; the values in the divs correspond to the first value in each object in the JSON. div 中的值对应于 JSON 中每个 object 中的第一个值。

This is my JSON:这是我的 JSON:

{"spaces":{
"space1": {
    "0": 1.0,
    "1": 2.0,
    "2": 0.0,
} 
"space2": {
    "0": 0.0,
    "1": 2.0,
    "2": 0.0,
}
"space3": {
    "0": 0.0,
    "1": 2.0,
    "2": 0.0,
}

and this is the class, which gets the JSON:这是 class,它得到 JSON:

import React, { Component } from "react";
import "./Maps.css";
import df3 from "./data/df3.json"
import sample from "./data/sample.json"


class Maps extends Component {
  constructor() {
    super();
    const data = df3;
    this.state = data
  }

  render()
  {
    console.log(this.state)
    var df4 = df3["Spaces"]
    var d1 = '';
    for (var key in df4)
    {
       var host = df4[key];


       d1 += '<div class="'+key+'" value="'+host[0]+'"/>';
    }
    console.log(d1)

    return (

      <div id="Maps">

     </div>

    )
  }
}

export default Maps

This is what the class outputs, a string wrapping a bunch of divs:这是 class 输出的内容,一个包含一堆 div 的字符串:

<div class="space1" value="1"/><div class="space2" value="0"/><div class="space3" value="0"/>

I would like to actually have these divs returned on the screen:我实际上希望在屏幕上返回这些 div:

return (
      <div id="Maps">
      // the list of divs should be returned
     </div>
    )

Any help, as always, is appreciated.一如既往地感谢任何帮助。

There are no arrays in your JSON data, so you'll need to convert it one. JSON 数据中没有 arrays,因此您需要将其转换为一个。 Object.values and Object.entries can do this. Object.valuesObject.entries可以做到这一点。 Then you can map as per usual.然后你可以像往常一样 map。

Lists and Keys列表和键

In the following I've used Object.entries to get an array of key-value pairs, ie [["space1", { "0": 1.0, "1", 2.0, "2": 0.0 }, ...]] .下面我使用Object.entries来获取键值对数组,即[["space1", { "0": 1.0, "1", 2.0, "2": 0.0 }, ...]] We don't need to do the same for the sub-object since it is keyed to already be "array-like" (remember arrays are just key-value pairs of { [index]: value } ).我们不需要对子对象做同样的事情,因为它的键值已经是“类数组”(记住 arrays 只是{ [index]: value }的键值对)。

import df3 from "./df3.json";

export default class App extends Component {
  state = {
    data: df3
  };

  render() {
    const { data } = this.state;
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>

        {Object.entries(data.spaces).map(([name, space]) => (
          <div key={name} className={name} value={space[0]} />
        ))}
      </div>
    );
  }
}

编辑静早-e6fgi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM