我有一个呈现Wordpress博客文章的组件。博客帖子包含常规的text/html标记,有时还包含带有元素的youtube嵌入。dangerouslySetInnerHTML去掉了这个iframe。我如何支持这种类型的内容。
发布于 2017-09-07 04:12:57
你可以通过创建一个React元素来解决这个问题,这个元素永远不会更新,但在创建时会使用常规Javascript插入你想要的html。注意这是非常不安全的!
const StaticHtml = React.createClass({
inject( element ) {
element.innerHTML = this.props.html;
},
shouldComponentUpdate() {
return false; //prevent React updates as it will get confused by the DOM it didn't put there!
},
render() {
return <div ref={ this.inject } />
}
});
const myHtml = `<iframe width="560" height="315" src="https://www.youtube.com/embed/jUjh4DE8FZA" frameborder="0" allowfullscreen></iframe>`;
ReactDOM.render( <StaticHtml html={ myHtml } />, document.getElementById("app") );<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='app'></div>
你不能更新" html“prop的值,因为React会被弄糊涂,所以一定要在html改变的时候销毁并重新创建元素( "key”prop对此很好)。
https://stackoverflow.com/questions/46083466
复制相似问题