如何在ReactJS中呈现HTML模板并从JSON响应中绑定数据

How to render HTML Template and bind data from JSON response in ReactJS?

本文关键字:JSON 响应 数据 绑定 HTML ReactJS      更新时间:2023-09-26

我必须使用reactjs呈现HTML模板。HTML模板是动态的,可以通过API调用。模板中有绑定html数据的规定。示例HTML模板如下,

<a target="_blank" href="{ad.url}">
    <div class="ads temp-1">
        <h2>{ad.name}</h2>
        <div class="adv-content">
            <div class="advs-image">
                <img src="{ad.image}" />
            </div>
            <div class="adv-desc">{ad.description}</div>
        </div>
    </div>
</a>

这里的ad是包含urlimagenamedescription等属性的对象

示例ad对象如下,

var ad = {
    "image": "testimage.jpg",
    "url": "http: //google.com",
    "name": "testadvertisement",
    "description": "testdescription"
}

我已经在AngularJs中使用$compile服务实现了这一点。

现在我想把它移动到reactjs。我试图使用reactjs render函数渲染,但它没有帮助。它将html呈现为字符串。

在reactjs中有任何编译功能吗?或者你能建议其他正确的方法吗?

感谢您的帮助。

我正确理解你应该使用dangerouslySetInnerHTML prop。

例如:

// SomeComponent.js
// other methods...
render() {
  // `htmlFromResponse` is your plain html string from response.
  return (
    <div dangerouslySetInnerHTML={{ __html: htmlFromResponse }} />
  );
}

使用此道具,您可以将普通html字符串呈现为div元素。


如果你从服务器获得html模板,并希望在呈现之前传递变量给它,你可以使用Mustache包:

import Mustache from 'mustache';
// template should contain variables in {{ ... }}
const html = Mustache.render(htmlFromServer, {
  variable: 'value'
});

接下来,您可以使用dangerouslySetInnerHTML prop渲染输出html

创建一个react组件来呈现HTML数据,然后将Json数据作为Prop传递给该组件。这将使React元素访问数据,并且当Json数据发生变化时,渲染的HTML将自动更新。

查看youtube上的一些react教程视频,这些视频将给你一个关于ReactJs如何工作的概述

这里是如何传递Props

https://jsfiddle.net/abhirathore2006/6a403kap/

var Hello = React.createClass({
  render: function() {
  console.log(this.props)
    return <div>Hello {this.props.name}
    <h5>{this.props.d1.name}</h5>
    id:{this.props.d1.id}
    </div>;
  }
});
ReactDOM.render(
  <Hello name="World" d1={{"name":"test","id":"5"}} />,
  document.getElementById('container')
);