You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GA4(Google Analytics 4)中创建带自定义参数的自定义事件

在React中给GA4发送带自定义参数的自定义事件

方法1:直接使用gtag.js(原生方式)

  • 确保React项目已正确加载GA4的gtag脚本,一般在public/index.html中添加:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-YOUR_TRACKING_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-YOUR_TRACKING_ID');
</script>
  • 在需要触发事件的组件中定义触发函数:
const sendGameOverEvent = () => {
  const currentUrl = window.location.href;
  const customData = { score: 100, level: 5, playerId: 'user_123' }; // 你的自定义JSON数据
  
  window.gtag('event', 'game_over', {
    action: 'message shown',
    label: currentUrl,
    data: JSON.stringify(customData) // 复杂对象建议转为字符串,也可拆分为单独参数
  });
};
  • 在合适时机调用函数,比如游戏结束的回调中:
useEffect(() => {
  if (gameIsOver) {
    sendGameOverEvent();
  }
}, [gameIsOver]);

方法2:使用react-ga4封装库

  • 安装依赖:
npm install react-ga4
# 或
yarn add react-ga4
  • 在项目入口文件(如src/index.js)初始化:
import ReactGA from 'react-ga4';

ReactGA.initialize('G-YOUR_TRACKING_ID');
  • 在组件中发送带参数的事件:
import ReactGA from 'react-ga4';

const sendGameOverEvent = () => {
  const currentUrl = window.location.href;
  const customData = { score: 100, level: 5 };
  
  ReactGA.event({
    action: 'message shown',
    label: currentUrl,
    data: JSON.stringify(customData)
  });
};

关键注意事项

  • 自定义参数需要先在GA4后台的事件编辑器中注册,否则无法在常规报告中展示(实时报告可能临时显示)。
  • 复杂JSON对象优先转为字符串传递,或拆分为独立参数,更便于后续维度分析。
  • 单页应用需确保gtag配置正确处理路由变化,避免事件追踪异常。

内容的提问来源于stack exchange,提问作者Ariel Rotem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:05:09