【发布时间】:2020-02-07 16:07:00
【问题描述】:
您好,我需要渲染一个包含脚本的 div 元素:
类似:
<div id="div-id-for-squaretile1" style="width: 300px; height: 250px;">
<script>
googletag.cmd.push(function() {
googletag.display('div-id-for-squaretile1');
});
</script>
</div>
我在我的组件中使用了一个钩子:
const GooglePublisherTag = ({ id }) => {
useGptSlot(id);
return <div id={id} />;
};
useGptSlot Hook 看起来像:
const useGptSlot = (id) => {
useEffect(() => {
const googletag = window.googletag || { cmd: [] };
googletag.cmd.push(() => {
googletag.display(id);
});
}, [id]);
};
但是我的代码不会在 div 中呈现脚本:
它改为输出:
<div id="div-id-for-squaretile1" data-google-query-id="CLGYq8Hhv-cCFcfbwAodGgcK0g" style="width: 250px; height: 250px;">
<div id="google_ads_iframe_/21848388897/Development/Geo-Landing_0__container__" style="border: 0pt none; width: 250px; height: 250px;"></div>
</div>
我如何做到这一点?
【问题讨论】:
-
假设的方式是dangerouslySetInnerHTML。但是,这行不通,因为您需要手动创建带有
document.createElement()的<script>标签,因为scripts added throughinnerHTMLwon't actually be interpretted 另请参阅MDN。 -
所以没有办法使用 react 来渲染那个脚本标签?
标签: javascript html css reactjs adsense