在从Firebase - React检索的html字符串中生成嵌入式gist

问题描述 投票:0回答:1

我有一个Post组件,它将使用从Firebase检索的内容设置innerHtml。

render() {
    return (
        <Panel>
            <Image src={this.state.img} alt={this.state.title} />
            <h2>{this.state.title}</h2>
            <p className='date'>{this.state.name}</p>
            <div className='text' ref='post'>
                <div dangerouslySetInnerHTML={{__html: this.state.content}} />
            </div>
        </Panel>
    )

要显示的内容存储在firebase中,如下所示:

{
      "id": 11,
      "title": "The Earth",
      "slug": "the-lazy-mans-guide-to-anything-about-princess",
      "img": "https://hd.unsplash.com/photo-1467321638755-7246fd0dc1f3",
      "summary": "<p>In as name to here them deny wise this. As rapid woody my he me which. Men but they fail shew just wish next put. Led all visitor musical calling nor her. Within coming figure sex things are. Pretended concluded did repulsive education smallness yet yet described. Had country man his pressed shewing. No gate dare rose he. Eyes year if miss he as upon.</p>",
      "content": "<p>In as name to here them deny wise this........

但是,因为React不会评估'内容'中的脚本标记,所以我无法嵌入一个要点。我尝试了几种替代方案但寻找建议。

reactjs firebase firebase-realtime-database gist
1个回答
1
投票

对不起延迟回答。干得好:

首先,让我们看看为什么在React Component中嵌入一个script标签是行不通的。 Michelle Tilley对这个问题给出了很好的答案。

Gist嵌入脚本使用document.write将构成嵌入式Gist的HTML写入文档的HTML。但是,当您的React组件添加脚本标记时,写入文档为时已晚。

- taken from here

如果你想在页面中嵌入一个Gist,你必须自己获取Gist的内容并将它们呈现在文档中。互联网上有许多特定工作的组件。这是我为自己的项目制作和使用的一个:super-react-app

然后,您就可以在项目中使用该组件,如下所示:

render() {
  return (
    <Panel>
      <Image src={this.state.img} alt={this.state.title} />
      <h2>{this.state.title}</h2>
      <p className='date'>{this.state.name}</p>
      <div className='text' ref='post'>

      {/* provide the url of the gist repository or the permalink of a gist file and you are ready to go */}
      <Gist url={this.state.content} />


      </div>
    </Panel>
  )
}

你只需要将Gist的url保存在对象content属性中,例如:

{
  "id": 11,
  "title": "The Earth",
  "slug": "the-lazy-mans-guide-to-anything-about-princess",
  "img": "https://hd.unsplash.com/photo-1467321638755-7246fd0dc1f3",
  "summary": "<p>In as name to here them deny wise this. As rapid woody my he me which. Men but they fail shew just wish next put. Led all visitor musical calling nor her. Within coming figure sex things are. Pretended concluded did repulsive education smallness yet yet described. Had country man his pressed shewing. No gate dare rose he. Eyes year if miss he as upon.</p>",

  "content": "https://gist.github.com/oneUser/5f55a83909a3fsb766934ffe802930df"

}

如果您不使用包管理器,上面的工具也可以在浏览器中使用UMD module。有关更多示例,请参阅项目的GitHub

© www.soinside.com 2019 - 2024. All rights reserved.