Ответ 1
Вот простой компонент, который обрабатывает показ объявлений, принимая во внимание лучшие возможности просмотра. (Спасибо Tracker1 за комментарии здесь, что очень помогло мне в этом вместе.)
import React from 'react';
import Waypoint from 'react-waypoint';
let instance = 0;
class Ads extends React.Component {
static propTypes = {
id: React.PropTypes.string,
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired,
adslot: React.PropTypes.string.isRequired
}
constructor() {
this.__id = 'ads-instance-' + ++instance;
this.displayAd = this.displayAd.bind(this);
}
get id() {
return this.props.id || this.__id;
}
componentDidMount() {
googletag.cmd.push(function() {
// Define the ad slot
googletag
.defineSlot(
this.props.adslot,
[this.props.width, this.props.height],
this.id
)
.addService(googletag.pubads());
// Start ad fetching
googletag.enableServices();
});
}
render() {
return (
<div style={{width:this.props.width, height:this.props.height}}>
<Waypoint onEnter={this.displayAd} />
<div id={this.id}></div>
</div>
);
}
displayAd() {
const id = this.id;
googletag.cmd.push(function() {
googletag.display(id);
});
}
}
export default Ads;
Я использовал контрольную точку для обеспечения правильной видимости (не загружая объявления, пока пользователи не увидят их). Когда путевая точка попадает в нижнюю часть области просмотра, когда пользователь прокручивается до нее, displayAd() показывает объявление. Смещение может быть усилено, но, надеюсь, это будет хорошей отправной точкой, чтобы дать вам общую идею.
Если на одной странице есть несколько рекламных мест, вы можете использовать уникальные идентификаторы вместо #ad-container
.