React JS如何让dangerouslySetInnerHTML中的脚本执行
React JS how to get script inside dangerouslySetInnerHTML executed
如何获取里面的脚本dangerouslySetInnerHTML得到执行?
class Page extends Component {
render() {
return (
<script
dangerouslySetInnerHTML={{ __html: `
console.log('hello world');
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'viewCart'
});
` }}
/>
);
}
}
我无法执行 console.log('hello world')
。有人可以帮忙吗?谢谢
您不能这样做,因为为了安全起见,脚本标签会被自动删除。
使用 javascript 的最佳方法是单独获取字符串并从 componentWillMount 或 componentDidMount[= 执行(或评估)它26=]
class Page extends Component {
componentDidMount() {
const jsCode = `
console.log('hello world');
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'viewCart'
})
`;
new Function(jsCode)();
}
// you can do something else here
render() {
return (
<noscript />
);
}
}
您显然可以使用任何字符串。我猜你可能正在从服务器加载它。
在上面的示例中,我使用了 new Function()()
,它与 eval()
非常相似,但速度更快。
我使用了 componentDidMount
所以我确定脚本在视图显示后执行。 Will 和 Did mount 之间的另一个区别是 Will mount 在通用(同构)应用程序的服务器端和客户端执行,而 Did mount 只会在通用应用程序的客户端执行。
由于 react-dom
创建它们的方式,脚本元素未被执行。
当 ReactDOM.createElement
收到类型 'script'
时,它使用 .innerHTML
而不是像您预期的那样使用 document.createElement
。
var div = document.createElement('div');
div.innerHTML = '<script></script>';
var element = div.removeChild(div.firstChild);
以这种方式创建脚本会将该元素上的 "parser-inserted" 标志设置为 true。这个标志告诉浏览器它不应该执行。
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0
如何获取里面的脚本dangerouslySetInnerHTML得到执行?
class Page extends Component {
render() {
return (
<script
dangerouslySetInnerHTML={{ __html: `
console.log('hello world');
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'viewCart'
});
` }}
/>
);
}
}
我无法执行 console.log('hello world')
。有人可以帮忙吗?谢谢
您不能这样做,因为为了安全起见,脚本标签会被自动删除。
使用 javascript 的最佳方法是单独获取字符串并从 componentWillMount 或 componentDidMount[= 执行(或评估)它26=]
class Page extends Component {
componentDidMount() {
const jsCode = `
console.log('hello world');
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'viewCart'
})
`;
new Function(jsCode)();
}
// you can do something else here
render() {
return (
<noscript />
);
}
}
您显然可以使用任何字符串。我猜你可能正在从服务器加载它。
在上面的示例中,我使用了 new Function()()
,它与 eval()
非常相似,但速度更快。
我使用了 componentDidMount
所以我确定脚本在视图显示后执行。 Will 和 Did mount 之间的另一个区别是 Will mount 在通用(同构)应用程序的服务器端和客户端执行,而 Did mount 只会在通用应用程序的客户端执行。
由于 react-dom
创建它们的方式,脚本元素未被执行。
当 ReactDOM.createElement
收到类型 'script'
时,它使用 .innerHTML
而不是像您预期的那样使用 document.createElement
。
var div = document.createElement('div');
div.innerHTML = '<script></script>';
var element = div.removeChild(div.firstChild);
以这种方式创建脚本会将该元素上的 "parser-inserted" 标志设置为 true。这个标志告诉浏览器它不应该执行。
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0