如何在 React 组件中嵌入 Google Ad Sense?

How to embed Google Ad Sense into React Component?

手头的问题专门针对 Google Ad Sense,但可以应用于任何脚本标记插入。我不明白如何将这样的东西添加到我的组件中。

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
                            <!-- My Ad-->
                            <ins class="adsbygoogle"
                                 style="display:block"
                                 data-ad-client="ca-pub-24524524"
                                 data-ad-slot="152452452"
                                 data-ad-format="auto"></ins>
                            <script>
                            (adsbygoogle = window.adsbygoogle || []).push({});
                            </script>

这样的事情有可能吗?

像这样的事情不需要第三方脚本。

Ad-Sense 需要第三方脚本,如下所示,如果您使用任何类型的模板(即...django 模板等),应在做出反应之前加载该脚本,或者将其放入模板中。 .)

将其放入模板中:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

然后把你的广告意义包括在内,删除评论(假设你使用的是 JSX)并把 google 给你的东西

google给了你什么:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> 
<!-- yourAdname-->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-23452425"
     data-ad-slot="24524524"
     data-ad-format="auto">
</ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

改成这样:

<ins className="adsbygoogle"
     style={{display:'block'}}
     data-ad-client="ca-pub-23452425"
     data-ad-slot="24524524"
     data-ad-format="auto">
</ins>

然后把实际的执行代码放在componentDidMount函数中

(adsbygoogle = window.adsbygoogle || []).push({});

我认为类似的解决方案适用于几乎所有相同的情况,而不仅仅是 Ad-Sense。

一个常见的误解是人们常常认为他们可以将脚本标记放在 dangerouslySetInnerHTML 属性中,但事实并非如此。它使用不会执行脚本标签的 setInnerHTML。

也许你可以使用这个反应组件:react-adsence。支持Google和百度

Google AdSence 为您提供以下广告代码:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- adapte_ad -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-7292810486004926"
     data-ad-slot="9220497478"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

那么如何将它包含在一个反应​​组件中呢?很简单:

  1. 写一个组件Class,并用styleclientslotformat.
  2. 给它props
  3. 在 componentDidMount 生命周期方法中执行 (adsbygoogle = window.adsbygoogle || []).push({});

然后得到react-adsence。如何使用?

import AdSence from 'react-adsence';

<AdSence.Google client='ca-pub-7292810486004926'
                slot='7806394673' />

在执行此操作之前,您应该在 HTML 中添加 script

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

注意:修改client/slot为你的。

基于 Chris Hawkes 的出色回答,这里是适用于 Typescript 的解决方案。

按照上面的步骤后,你会在componentDidMount()中得到错误,因为编译器不知道adsbygoogle变量和adsbygoogle属性 Window 对象。

解决这些问题:

  1. declare var adsbygoogle: any; 全局(我在 index.tsx 中做到了,在所有组件之上)
  2. componentDidMount()中写(adsbygoogle = (window as any).adsbygoogle || []).push({});