简体   繁体   English

如何在 react js 中嵌入 google adsense

[英]How to embed google adsense in react js

I am beginner in reactjs and I want to embed google inline ads in loops.我是 reactjs 的初学者,我想在循环中嵌入谷歌内联广告。 The ad is showing only at first time.该广告仅在第一次展示。 When I inspect the element tag shows in loop.当我检查循环中显示的元素标签时。 Can I please know how to solve this issue?我可以知道如何解决这个问题吗?

Google adsense code:-谷歌广告代码:-

 var ScheduleRow = React.createClass({
 var rows = _.map(scheduleData.schedules, function(scheduleList, i) {
  var divStyle = { display: "block"};  
  return (  
    <ins className="adsbygoogle"
        style={divStyle}
        data-ad-client="ca-pub-3199660652950290"
        data-ad-slot="6259591966"
        data-ad-format="auto" key={i}>
    </ins>
  ); 
 });

return (
    <span>
        {rows}
    </span>
);
});

Output:- Output:-

输出图像

Inspect Element Output:-检查元素 Output:-

检查元素输出

This seems a duplicated question.这似乎是一个重复的问题。 You can find it in here .你可以在这里找到它。 But I think it isn't 100% clear.但我认为这不是 100% 清楚。 So, I came across once with this blog post which is more clear.所以,我在这篇博客文章中遇到过一次,它更清楚。

From Google you have this:从谷歌你有这个:

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

<ins class="adsbygoogle"
      style="display:block"
      data-ad-client="ca-pub-12121212"
      data-ad-slot="12121212"
      data-ad-format="auto"/>

<script>
  (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Now, in your react app:现在,在您的 React 应用程序中:

Include the following snippet in your index.html在 index.html 中包含以下代码段

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

Create your react component like:创建你的反应组件,如:

import React from 'react';

export default class AdComponent extends React.Component {
  componentDidMount () {
    (window.adsbygoogle = window.adsbygoogle || []).push({});
  }

render () {
    return (
        <ins className='adsbygoogle'
          style={{ display: 'block' }}
          data-ad-client='ca-pub-12121212'
          data-ad-slot='12121212'
          data-ad-format='auto' />
    );
  }
}

Now, to render it multiple times you can simply wrap the ins html tag with an iterator like map .现在,要多次渲染它,您可以简单地用map类的迭代器包装ins html 标签。 However, I don't fully understand your need here.但是,我不完全理解您在这里的需求。

If you want to show them all at once, then do your map like this .如果你想一次显示它们,那么像这样做你的地图。

If you want to randomise your ad, add a state to your component and a tick state so that it can re-render every X seconds.如果您想随机化您的广告,请为您的组件添加一个状态和一个勾选状态,以便它可以每 X 秒重新渲染一次。 Check it in this SO answer这个SO 答案中检查它

Notes:注意事项:

  1. From you google sense add, rename class attribute to className从您的 google 意义上添加,将class属性重命名为className
  2. Update style attribute to be wrapped like this: style={{ display: 'block' }}更新style属性以这样包装: style={{ display: 'block' }}

Answer by @jpgbarbosa is great. @jpgbarbosa 的回答很棒。 I'll add better practice for Server Side Rendered React applications which have multiple pages, for scalability, I suggest you use this method to keep code base maintainable.我将为具有多个页面的服务器端渲染 React 应用程序添加更好的实践,为了可扩展性,我建议您使用这种方法来保持代码库的可维护性。

export default class HomePage extends React.Component {
  componentDidMount() {
    const installGoogleAds = () => {
      const elem = document.createElement("script");
      elem.src =
        "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
      elem.async = true;
      elem.defer = true;
      document.body.insertBefore(elem, document.body.firstChild);
    };
    installGoogleAds();
    (adsbygoogle = window.adsbygoogle || []).push({});
  }

  render() {
    return (
      <ins className='adsbygoogle'
           style={{ display: 'block' }}
           data-ad-client='ca-pub-12121212'
           data-ad-slot='12121212'
           data-ad-format='auto' />
    );
  }
}

I am beginner in reactjs and I want to embed google inline ads in loops.我是reactjs的初学者,我想将Google嵌入式广告嵌入循环中。 The ad is showing only at first time.广告仅在第一次展示。 When I inspect the element tag shows in loop.当我检查元素标记显示在循环中。 Can I please know how to solve this issue?请问如何解决这个问题?

Google adsense code:- Google adsense代码:-

 var ScheduleRow = React.createClass({
 var rows = _.map(scheduleData.schedules, function(scheduleList, i) {
  var divStyle = { display: "block"};  
  return (  
    <ins className="adsbygoogle"
        style={divStyle}
        data-ad-client="ca-pub-3199660652950290"
        data-ad-slot="6259591966"
        data-ad-format="auto" key={i}>
    </ins>
  ); 
 });

return (
    <span>
        {rows}
    </span>
);
});

Output:-输出:-

输出图像

Inspect Element Output:-检查元素输出:-

检查元素输出

If you have the Adsense script loading in one component and ad slot it another, the script might not have loaded while the second component is mounted.如果您在一个组件中加载 Adsense 脚本并在另一个组件中插入广告位,则在安装第二个组件时可能未加载该脚本。 Due to this, window.adsbygoogle will be evaluated to [] and the ad will not load.因此, window.adsbygoogle将评估为 [],广告将不会加载。 This will even affect the auto ads if you are using both auto ads and ad units.如果您同时使用自动广告和广告单元,这甚至会影响自动广告。

This is the solution I have implemented:这是我实施的解决方案:

import React, { useEffect } from "react"

const SideAd = () => {
  useEffect(() => {
    const pushAd = () => {
      try {
        const adsbygoogle = window.adsbygoogle
        console.log({ adsbygoogle })
        adsbygoogle.push({})
      } catch (e) {
        console.error(e)
      }
    }

    let interval = setInterval(() => {
      // Check if Adsense script is loaded every 300ms
      if (window.adsbygoogle) {
        pushAd()
        // clear the interval once the ad is pushed so that function isn't called indefinitely
        clearInterval(interval)
      }
    }, 300)

    return () => {
      clearInterval(interval)
    }
  }, [])
  return (
    <ins
      className="adsbygoogle"
      style={{ display: "inline-block", width: "300px", height: "250px" }}
      data-ad-client="ca-pub-xxxxxx"
      data-ad-slot="xxxxx"
    ></ins>
  )
}

export default SideAd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM