簡體   English   中英

在React中使用analytics.js而不使用react-ga

[英]Using analytics.js in React without react-ga

我想不使用react-ga軟件包將谷歌分析集成到我的react應用程序中。 具體來說,我希望能夠在react組件中訪問ga函數。 如果我將analytics.js腳本導入html中,如何訪問ga函數? 當我嘗試console.log(window.ga) ,被告知未定義。 謝謝!

 class App extends React.Component { render() { console.log(window.ga); return ( <h1>This is a react app!</h1> ); } } ReactDOM.render(<App />, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <script async src='//www.google-analytics.com/analytics.js'></script> <div id="app"></div> 

這是您應該包括的代碼:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

或者,如果您想保留指向analytics.js的鏈接,

window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;

我建議使用細分分析庫並遵循我們的React快速入門指南 您可以使用1個單一API在React組件中使用react-router和用戶行為跟蹤頁面訪問。 這是一個使用React事件處理程序跟蹤User Signup點擊的示例:

export default class SignupButton extends Component {
  trackEvent() {
    window.analytics.track('User Signup');
  }

  render() {
    return (
      <button onClick={this.trackEvent}>
        Signup with Segment today!
      </button>
    );
  }
}

我是https://github.com/segmentio/analytics-react的維護者。 如果您有興趣嘗試使用多種分析工具(我們支持超過250個目的地),而無需編寫任何其他代碼,則使用細分功能,您可以通過輕按一下開關來切換不同的目的地。 🙂

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM