在React index.html中为Branch SDK访问变量

时间:2018-10-08 19:34:39

标签: javascript reactjs sdk branch

如果将此SDK添加到我的index.html文件中,我将无法在其他组件中访问它。还有另一种方法吗?

  <script>
    // load Branch
      (function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode autoAppIndex banner closeBanner closeJourney creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode trackCommerceEvent logEvent disableTracking".split(" "), 0);
    // init Branch
    branch.init('key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt');
  </script>

尝试通过这种方式在另一个组件中进行访问。

var options = { no_journeys: true };
branch.init('key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt', options, function(err, data) {
  console.log(err, data); 
});

2 个答案:

答案 0 :(得分:1)

您可以将branch绑定到window属性,并从整个应用程序访问它们。

初始化:

<head>
  <script>
    branch.init('key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Swt', options, function(err, data) {
      window.__BRANCH__ = data;
    });
  </script>
</head>

用法:

const Component = () => (
  <button 
    onClick={() => {
      // You have access to window.__BRANCH__
    }}
  >
    Button
  </button>
);

答案 1 :(得分:1)

使用npm

https://github.com/BranchMetrics/web-branch-deep-linking#quick-install

npm i branch-sdk

然后:

import branch from 'branch-sdk'

branch.init(...)