我正在创建我的第一个真正的反应应用...
在我的主页上,我有一个显示随机推荐的部分
建议从JSON doc加载到一个数组中,我使用setInterval来更改div容器的内容。
我遇到的问题是来自json的一些数据有HTML字符(大多数是带有className的跨度,可以实现特殊的样式),并且反应似乎正在逃避这些HTML字符,因为它们是作为标准文本插入的。
如何将此内容作为HTML插入?
编辑:正如Andy指出的那样,我发现了其他相关问题,但是他们似乎并没有在我的场景中提供帮助,因为他们在渲染方法中使用它,我是不
编辑2:为了澄清一点,为什么这个问题与qas声称重复的问题有所不同:当我使用方法dangerouslySetInnerHTML
时,我收到以下错误:控制台:
错误:对象无效作为React子对象(找到:带有键{__html}的对象)
我后来发现有人明确提到该方法对儿童不起作用。
现在,我的方案有什么解决方案?
任何帮助将不胜感激。
以下是相关代码:
var React = require('react');
var Home = React.createClass({
getInitialState: function() {
return {
recCtr: 0,
allRecs: this.prepareRecs(/*This function gets and prepares the array of recommendations*/),
currentRec: {}
}
},
componentDidMount: function() {
this.setState({currentRec: this.state.allRecs[0]});
this.startRecsInterval().bind(this);
},
startRecsInterval() {
setInterval(function(){
let ctr = this.state.recCtr + 1;
if (ctr >= this.state.allRecs.length) ctr = 0;
this.setState({recCtr: ctr, currentRec: this.state.allRecs[ctr]})
}.bind(this), 5000)
},
render() {
return (
<div id="mainDiv">
<div id="recommendations">
<div id="comment">{ this.state.currentRec.comment }
<span className="author">{ this.state.currentRec.author }</span>
</div>
</div>
</div>
)
}
})
module.exports = Home;