如何在Gatsby.js中使用gatsby-plugin-google-gtag?

时间:2019-07-08 22:15:42

标签: reactjs google-tag-manager google-adwords gatsby

我刚刚在gatsby-plugin-google-gtag文件中安装了gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        trackingIds: [
          "UA-XXXXXXXXX-X", // Google Analytics / GA
          "AW-XXXXXXXXX" // Google Ads / Adwords / AW
        ],
        pluginConfig: {
          head: true        
        },
      }
    }
  ]
}

然后我将这个事件添加到我的表单上,应该可以吗?

class Form extends Component {

    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        window.gtag("conversion", "click", { send_to: ["AW-XXXXXXXXX/-XXXXXXXXXXXXXXXX"]})
    }    

    render() {
        return (
            <Div className='au'>
            <form action="https://formspree.io/my@emailaddress.io" method="POST">
                <InputName type="name" name="name" placeholder="Your Name"/>
                <InputMail type="email" name="email" placeholder="Your Mail"/>
                <Button type="submit" onClick={this.handleClick}>Contact us</Button>
            </form>
            </Div>
        )
    }
}

export default Form;

2 个答案:

答案 0 :(得分:2)

来自文档:

  

此插件仅在生产模式下有效!

您的配置也不错,只需确保您的trackingId正确即可

答案 1 :(得分:0)

handleClick() { window.gtag("event", "conversion", { send_to: ["AW-XXXXXXXXX/-XXXXXXXXXXXXXXXX"]}) } 应该是:

gtag

gtag("event", "<event_name>", {<event_params>}); 格式为:

gtag

有关{{1}} here的其他信息。