【问题标题】:Render html with javascript/jquery string in react.js在 react.js 中使用 javascript/jquery 字符串渲染 html
【发布时间】:2017-01-22 15:09:19
【问题描述】:
我们可以在 react 渲染中使用 dangerouslySetInnerHTML 来在 dom 中正确加载 html 字符串。但是,如果我们可以在 html 字符串中添加一些 javascript 或 jquery 代码,我们该怎么办。例如下面。带有 javascript/jquery 的 html 来自 api 响应。
var htmlString = "<div>Hello</div><script>alert('hello')</script>"
【问题讨论】:
标签:
javascript
html
reactjs
【解决方案1】:
您可以通过以下方式找到脚本部分和其他部分:
var div = document.createElement('div');
div.innerHTML = htmlString;
var scripts = div.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
然后您可以使用scripts 和div.innerHTML
添加脚本标签的方法有很多种,您可以在此处查看其中的一些:
Adding script tag to React/JSX