首页 > 解决方案 > Gatsbyjs + Google 分析 - 跟踪自定义事件?

问题描述

是否有可能使用 gatsby 和谷歌分析来跟踪自定义事件?

标签: javascriptreactjsgoogle-analyticsevent-handlinggatsby

解决方案


我已经将ReactGA与 Gatsby 结合使用并取得了很好的成功。

对于基本的事件跟踪——比如记录点击的链接——它非常容易使用。您在组件中创建一个日志记录函数,该函数访问ReactGA.event然后在您的渲染函数中使用onClick.

记录 PDF 下载的示例组件:

import React from 'react'
import Link from 'gatsby-link'
import ReactGA from 'react-ga'

import logo from './logo.png'
import financials from './Annual_Report_Financials_2017_FINAL.pdf'

class LoggingDownload extends React.Component {
  logger() {
    // Detect each click of the financial PDF
    ReactGA.event({
      category: 'Financial Download',
      action: 'User clicked link to view financials'
    })
  }

  render() {
    return (
      <div>
        <nav className="nav-container">
          <Link to="/locations">
            <img className="logo" src={logo} alt="Logo" />
          </Link>
          <ul className="nav-item-container">
            <li className="nav-item">
              <a href="/shortsignup/" target="_blank">Join Us</a>
            </li>
            <li className="nav-item">
              <a href={financials} onClick={this.logger} target="_blank" id="financials-pdf">Financials</a>
            </li>
          </ul>
        </nav>
      </div>
    )
  }
}
export default LoggingDownload

还有很多用例——查看 ReactGA 文档。

另外:不要忘记ggatsby-plugin-google-analytics在您的gatsby-config.js文件中包含作为使上述内容正常工作的依赖项:

{
  resolve: `gatsby-plugin-google-analytics`,
  options: {
    trackingId: "UA-#########-##",
    // Puts tracking script in the head instead of the body
    head: false,
    // Setting this parameter is optional
    respectDNT: true,
  }
}

推荐阅读