将 Google Analytics 添加到 React [英] Adding Google Analytics to React

查看:50
本文介绍了将 Google Analytics 添加到 React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Google Analytics 添加到 React Web 应用程序.

I am trying to add Google Analytics to a React Web Application.

我知道如何在 HTML/CSS/JS 站点中执行此操作,并且我也将其集成到了 AngularJS 应用程序中.但是,当涉及到反应时,我不太确定如何去做.

I know how to do it in HTML/CSS/JS sites and I have integrated it in an AngularJS app too. But, I'm not quite sure how to go about it when it comes to react.

使用 HTML/CSS/JS,我刚刚将它添加到每个页面.

With HTML/CSS/JS, I had just added it to every single page.

我对 AngularJS 所做的是将 GTM 和 GA 脚本添加到 index.html 并将 UA 标签添加到 HTML div(和按钮)以获得点击.

What I had done with AngularJS was adding GTM and GA script to index.html and added UA-labels to the HTML divs (and buttons) to get clicks.

我如何使用 React 做到这一点?

请帮忙!

推荐答案

更新:2019 年 2 月
看到这个问题被搜索了很多,我决定扩大我的解释.
要将 Google Analytics 添加到 React,我建议使用 React-GA.
通过运行添加:
npm install react-ga --save

初始化:
在根组件中,通过运行进行初始化:

Initialization:
In a root component, initialize by running:

import ReactGA from 'react-ga';
ReactGA.initialize('Your Unique ID');

报告页面浏览量:

ReactGA.pageview(window.location.pathname + window.location.search);

要报告自定义事件:

ReactGA.event({
  category: 'User',
  action: 'Sent message'
});

可以在 github 存储库

此 IMO 的最佳实践是使用 react-ga.看看 github 代表

The best practice for this IMO is using react-ga. Have a look at the github rep

这篇关于将 Google Analytics 添加到 React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆