在react组件中加载Amazon脚本

时间:2019-02-14 10:34:14

标签: javascript reactjs typescript script-tag

我的react组件中包含以下脚本,当我刷新该组件时该脚本可以工作。但是,当我在路线之间导航时,它不起作用。

import { inject, observer } from 'mobx-react'
import React from 'react'

@inject('store')
@observer
export default class Ads extends React.Component<{}> {
  public componentDidMount() {
    const div = document.createElement('div')
    div.id = 'amzn_assoc_ad_div_adunit0_0'
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US`
    const s = document.createElement('script')
    s.type = 'text/javascript'
    const code = `amzn_assoc_placement = "adunit0"; 
    amzn_assoc_tracking_id = "teamhansel-20";
    amzn_assoc_ad_mode = "search";
    amzn_assoc_ad_type = "smart";
    amzn_assoc_marketplace = "amazon";
    amzn_assoc_region = "US";
    amzn_assoc_default_search_phrase = "Search Amazon For Cash Back";
    amzn_assoc_default_category = "All";
    amzn_assoc_linkid = "";
    amzn_assoc_search_bar = "true";
    amzn_assoc_search_bar_position = "top";
    amzn_assoc_title = "Shop Related Products"`  
    s.appendChild(document.createTextNode(code))
    const dom = document.getElementById('amazon-search-container')
    if(dom) {
      dom.appendChild(s)
      dom.appendChild(script)
    }
  }

  public render() {
    return (
      <div key={Math.random()}>
        <div className="mt-3 item__wrapper" id="amazon-ads-container"> 
          <div id="amazon-search-container">&nbsp;</div>
          <div id="amzn_assoc_ad_div_adunit0_0">&nbsp;</div>
        </div>  
      </div>
    )
  }
} 

您可以简单地设置一个react项目并尝试一下...请!!!

谢谢!

0 个答案:

没有答案