我从API获取对象列表。每个对象的值之一是纯字符串:
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"
我想将这个纯字符串转换为html。我怎么做?
编辑:
我想做的是像这样在React中的列表上进行映射:
const list = props.responseData.map(item => (
<li key={item.pageid}>
{item.title}
<br />
{item.snippet}
</li>
));
片段之一显示为纯字符串,而不显示为HTML代码。编写item.snippet.innerHTML无效。它显示一个空列表。
最佳答案
我想到了。我需要将其放入具有特殊属性的div中:
<div dangerouslySetInnerHTML={{ __html: item.snippet }} />
实时示例
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>