React 接入

澄泓统计提供 React 专用组件库,支持 React 16.8+(Hooks),自动集成 React Router / Next.js 路由,支持 TypeScript。

💡 前置条件:请先在后台添加站点获取 Tracking ID(格式如 tid_xxxxxxxxxx)。

React SPA 接入(Vite/CRA)

1. 在根组件包裹 AnalyticsProvider

jsx
// main.jsx / main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { AnalyticsProvider } from 'light-analytics/react'
import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <AnalyticsProvider
        tid="tid_xxxxxxxxxx"
        // serverUrl="https://your-domain"  // 私有化部署时填写
        // debug={false}
        // consent="auto"
        autoTrackPageviews={true}  // 自动追踪路由切换
      >
        <App />
      </AnalyticsProvider>
    </BrowserRouter>
  </React.StrictMode>
)
✅ 自动功能:AnalyticsProvider 放在 BrowserRouter 内部,会自动监听路由变化,无需手动上报页面浏览。

2. 使用 Hooks

在任意函数组件中使用 useAnalytics() Hook:

jsx
import { useAnalytics } from 'light-analytics/react'

function CheckoutButton() {
  const { trackEvent, identify } = useAnalytics()

  const handlePurchase = () => {
    // 上报自定义事件
    trackEvent('purchase', {
      amount: 99,
      product: 'Pro版',
      currency: 'CNY'
    })
  }

  const handleLogin = (user) => {
    // 关联用户信息
    identify(user.id, {
      plan: user.plan,
      email: user.email
    })
  }

  return <button onClick={handlePurchase}>立即购买</button>
}

3. Class 组件中使用

jsx
import { withAnalytics } from 'light-analytics/react'

class MyComponent extends React.Component {
  handleClick = () => {
    this.props.analytics.trackEvent('button_click', {
      location: 'hero'
    })
  }
  render() {
    return <button onClick={this.handleClick}>点击</button>
  }
}

export default withAnalytics(MyComponent)

4. 手动追踪页面浏览(如果关闭 autoTrackPageviews)

jsx
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useAnalytics } from 'light-analytics/react'

function usePageTracker() {
  const location = useLocation()
  const { trackPageview } = useAnalytics()

  useEffect(() => {
    trackPageview(location.pathname + location.search)
  }, [location])
}

Next.js App Router 接入(Next 13+)

1. 创建客户端组件 Provider

tsx
// app/analytics-provider.tsx
'use client'

import { AnalyticsProvider } from 'light-analytics/react'

export function AnalyticsWrapper({ children }: { children: React.ReactNode }) {
  return (
    <AnalyticsProvider
      tid="tid_xxxxxxxxxx"
      autoTrackPageviews={true}
      // Next.js App Router 用 usePathname 监听,无需传 router
    >
      {children}
    </AnalyticsProvider>
  )
}

2. 在根 layout 中引入

tsx
// app/layout.tsx
import { AnalyticsWrapper } from './analytics-provider'

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <AnalyticsWrapper>
          {children}
        </AnalyticsWrapper>
      </body>
    </html>
  )
}

3. 在 Server Component 中使用

Server Component 不能直接使用 Hooks,需要在 Client Component 中使用,或使用 analytics() 服务端上报(仅事件,不计入访客):

tsx
// app/actions.ts (Server Action)
'use server'
import { trackServerEvent } from 'light-analytics/server'

export async function handleFormSubmit(formData: FormData) {
  // 服务端上报事件(不关联访客session)
  await trackServerEvent('form_submit', {
    form_id: 'contact',
    has_email: !!formData.get('email')
  }, { tid: 'tid_xxxxxxxxxx' })

  // ... 处理业务逻辑
}

Next.js Pages Router 接入(Next 12/13)

1. 在 _app.js 中包裹 Provider

jsx
// pages/_app.js
import { AnalyticsProvider } from 'light-analytics/react'
import { useRouter } from 'next/router'
import { useEffect } from 'react'

export default function MyApp({ Component, pageProps }) {
  const router = useRouter()

  return (
    <AnalyticsProvider
      tid="tid_xxxxxxxxxx"
      router={router}  // 传入 Next.js router 自动追踪
    >
      <Component {...pageProps} />
    </AnalyticsProvider>
  )
}

Remix 接入

1. 在 root.tsx 中初始化

tsx
// app/root.tsx
import { AnalyticsProvider, useAnalytics } from 'light-analytics/react'
import { useLocation } from '@remix-run/react'
import { useEffect } from 'react'

export default function App() {
  return (
    <html lang="zh-CN">
      <head>...</head>
      <body>
        <AnalyticsProvider tid="tid_xxxxxxxxxx">
          <AnalyticsPageTracker />
          <Outlet />
          <Scripts />
        </AnalyticsProvider>
      </body>
    </html>
  )
}

function AnalyticsPageTracker() {
  const location = useLocation()
  const { trackPageview } = useAnalytics()
  useEffect(() => {
    trackPageview(location.pathname + location.search)
  }, [location])
  return null
}

API 参考

AnalyticsProvider Props

  • tid (必填):Tracking ID
  • router:路由实例(React Router/Next Router),传入后自动追踪
  • serverUrl:私有化部署地址
  • debug:调试模式,默认 false
  • consent'auto' | 'explicit'
  • autoTrackPageviews:自动追踪页面浏览,默认 true
  • autoTrackClicks:自动追踪按钮点击,默认 true

useAnalytics() 返回值

js
const {
  trackPageview,   // (path?, title?) => void  上报页面浏览
  trackEvent,      // (name, props?) => void    上报自定义事件
  identify,        // (userId, traits?) => void 关联用户
  grantConsent,    // () => void               用户同意采集
  denyConsent,     // () => void               用户拒绝采集
  setDebug         // (bool) => void           开关调试
} = useAnalytics()
⚠️ TypeScript 支持:所有 Hook 和组件均内置 TypeScript 类型定义,trackEvent 的属性值支持 string | number | boolean 类型。