gpt4 book ai didi

javascript - 如何将 JS 脚本标签添加到 React App 的 ComponentDidMount 中?

转载 作者:行者123 更新时间:2023-11-30 11:15:40 26 4
gpt4 key购买 nike

我正在努力使用 Google 优化工具。我需要在我的页面中添加这个标签:

<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-X':true});</script>

为了在 React 中完成这项工作,我正在尝试以下操作:

import React from 'react';

const MarketingPage = class extends React.Component {
compomentDidMount = () => {
(function(a, s, y, n, c, h, i, d, e) {
s.className+=' '+y;
h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-X':true}
);
}

React 不喜欢这个。我收到以下错误:

将调用移动到包含函数的括号中

是否可以重写 Google Optimize 所需的代码以实现 React、linter 友好?

谢谢

最佳答案

我不认为是 React 给了你这个警告,而是你的 linter。

您可以将您的函数放在一个变量中,然后立即调用它。

const MarketingPage = class extends React.Component {
compomentDidMount() {
const analytics = function(a, s, y, n, c, h, i, d, e) {
s.className+=' '+y;
h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
};

analytics(window,document.documentElement,'async-hide','dataLayer',4000,{'GTM-X':true});
}
}

关于javascript - 如何将 JS 脚本标签添加到 React App 的 ComponentDidMount 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51680094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com