如何在Reactjs中呈现HTML元素?

时间:2018-07-11 11:24:18

标签: javascript html reactjs

我真的是ReactJS的新手,并且仍然在学习它。

我试图返回文件树视图,但是它显示了页面上的所有元素,如下所示。

<ul className='folder-container'>
  <li className='folder-item'> app </li>
  <li className='folder-wrapper'><ul className='folder-container'><ul className='folder-container'>
  <li className='file-item'> index.html </li></ul><ul className='folder-container'>
  <li className='folder-item'> js </li>
  <li className='folder-wrapper'>
<ul className='folder-container'>....

我想返回页面上文件夹内所有项目的列表。我以为可以使用组件内部的函数将其返回。我做得对吗?

我的代码:

class Filetree extends Component {
  constructor({ props }) {
    super(props);
    this.state = {
      folders: [
        {
          type: "dir",
          name: "app",
          children: [
            {
              type: "file",
              name: "index.html"
            },
            {
              type: "dir",
              name: "js",
              children: [
                {
                  type: "file",
                  name: "main.js"
                },
                {
                  type: "file",
                  name: "app.js"
                },
                {
                  type: "file",
                  name: "misc.js"
                }
              ]
            }
          ]
        },
        {
          type: "dir",
          name: "css",
          children: [
            {
              type: "file",
              name: "reset.css"
            },
            {
              type: "file",
              name: "main.css"
            }
          ]
        }
      ]
    };
  }

  displayJsonTree(data) {
    var htmlRetStr = `<ul className='folder-container'>`;
    for (var key in data) {
      if (typeof data[key] === "object" && data[key] !== null) {
        htmlRetStr += this.displayJsonTree(data[key]);
        htmlRetStr += `</ul>`;
      } else if (data[key] === "dir") {
        htmlRetStr += `<li className='folder-item'> ${
          data["name"]
        } </li> <li className='folder-wrapper'>`;
      } else if (key === "name" && data["type"] !== "dir") {
        htmlRetStr += `<li className='file-item'> ${data["name"]} </li>`;
      }
    }
    return htmlRetStr;
  }

  render() {
    const { folders } = this.state;

    return <div>{this.displayJsonTree(folders)}</div>;
  }
}

1 个答案:

答案 0 :(得分:2)

如果字符串中包含HTML,则可以使用dangerouslySetInnerHTML

render() {
  const { folders } = this.state;

  return <div dangerouslySetInnerHTML={{ __html: this.displayJsonTree(folders) }} />;
}