内联条件不加载脚本reactjs nextjs app
Inline condition doesn't load script reactjs nextjs app
我对加载脚本的内联条件有疑问。这些条件有效,因为标签向我显示了文本,但对于脚本它不起作用。我该如何解决。
const cookie = new Cookies().get('cookiesAccepted');
const [loadScript,setLoadScript]= useState(cookie);
function cookieAccepted(){
setLoadScript(true);
}
return(
{loadScript &&
<h1>test</h1>
}
<Cookie meta={cookieAccepted.bind(this)}/>
{ loadScript &&
<script
async
src="https://www.googletagmanager.com/gtag/"
/>
}
{loadScript &&
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '********', {
page_path: window.location.pathname,
});
`,
}}
/>
}
)
推荐使用next js中的Script函数
import Script from 'next/script';
除了添加标签,您还可以这样做:
{cookieAccepted && (
<Script src={`https://www.googletagmanager.com/gtag/`}/>
)}
查看此 link 以获得更多参考:
https://nextjs.org/docs/api-reference/next/script
我对加载脚本的内联条件有疑问。这些条件有效,因为标签向我显示了文本,但对于脚本它不起作用。我该如何解决。
const cookie = new Cookies().get('cookiesAccepted');
const [loadScript,setLoadScript]= useState(cookie);
function cookieAccepted(){
setLoadScript(true);
}
return(
{loadScript &&
<h1>test</h1>
}
<Cookie meta={cookieAccepted.bind(this)}/>
{ loadScript &&
<script
async
src="https://www.googletagmanager.com/gtag/"
/>
}
{loadScript &&
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '********', {
page_path: window.location.pathname,
});
`,
}}
/>
}
)
推荐使用next js中的Script函数
import Script from 'next/script';
除了添加标签,您还可以这样做:
{cookieAccepted && (
<Script src={`https://www.googletagmanager.com/gtag/`}/>
)}
查看此 link 以获得更多参考: https://nextjs.org/docs/api-reference/next/script