简体   繁体   English

将纯文本反应为html代码

[英]React plain text to html code

I get a list of objects from the API. 我从API获得了一个对象列表。 One of the values of each object is a plain string: 每个对象的值之一是纯字符串:

snippet: "Chainsmokers were re-formed as an EDM DJ duo in 2012 under the management of <span class="searchmatch">Adam</span> Alpert in New York City. Pall, who had grown up DJing, was introduced to"

I'd like to convert this plain string to be interpreted as html. 我想将此纯字符串转换为html。 How do I do that? 我怎么做?

Edit: What I try to do is map over a list in React like so: 编辑:我尝试做的是映射React中的列表,如下所示:

const list = props.responseData.map(item => (
<li key={item.pageid}>
  {item.title}
  <br />
  {item.snippet}
</li>
));

The snippet one is displayed as a plain string, not as HTML code. 代码段显示为纯字符串,而不是HTML代码。 Writing item.snippet.innerHTML doesn't work. 编写item.snippet.innerHTML不起作用。 It displays an empty list. 它显示一个空列表。

I figured it out. 我想到了。 I need to put it inside a div with a special attribute: 我需要将它放在具有特殊属性的div中:

<div dangerouslySetInnerHTML={{ __html: item.snippet }} />

LIVE EXAMPLE 现场例子

 class App extends React.Component { constructor() { super(); this.state = { snippet: `Chainsmokers were re-formed as an EDM DJ duo in 2012 under the management of <span class="searchmatch">Adam</span> Alpert in New York City. Pall, who had grown up DJing, was introduced to` } } render() { return ( <div dangerouslySetInnerHTML={{ __html: this.state.snippet }} /> ); } } ReactDOM.render(<App />, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='root'></div> 

If you want to display obj.snippet in a div with a specified id , this would be as simple as 如果要在具有指定id的div中显示obj.snippet ,这将非常简单

HTML HTML

<div id="myDiv"></div>

JS JS

document.getElementById('myDiv').innerHTML = obj.snippet;

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

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