[英]React: How to use same component twice in same page but loading one script tag for both just one time
I created a react component that I want to use twice(or more) inside my page, and I need to load a script tag for it inside the head of my page but just once! 我创建了一个React组件,我想在页面内使用两次(或多次),并且需要在页面的头部加载一个脚本标签,但是只能加载一次! I mean even if I use the component twice or more in the page it should add the script tag just once in the head.
我的意思是,即使我在页面中使用组件两次或更多次,它也应该仅在头部添加一次脚本标记。 The Problem is that this script tag should be absolutely a part of the component and not statically inserted in the head of my page.
问题在于此脚本标记绝对应该是组件的一部分,而不是静态地插入到页面的开头。
Can anyone help me to make the magic happens? 谁能帮助我实现奇迹? Thanks a lot in advance!
在此先多谢!
You can set the state of the parent component to keep in memory that the script is already added. 您可以设置父组件的状态以将脚本已添加到内存中。
if (!this.state.scriptAdded) {
// Add script tag
this.setState({ scriptAdded: true });
}
You can give react-helmet
a try for managing changes to your <head>
from within React components. 您可以尝试使用React
react-helmet
从React组件中管理对<head>
更改。
In particular, you can check this example where rendering the same element four times only adds the script tag once. 特别是,您可以检查此示例 ,其中四次渲染同一元素仅添加一次脚本标签。
For completeness, the relevant code from the example (although the interesting part is to see how it executes): 为了完整起见,使用示例中的相关代码(尽管有趣的部分是看它如何执行):
import { Helmet } from "react-helmet";
function ComponentWithHeader() {
return (
<div>
<div>Oh hi</div>
<Helmet>
<script src="fake-url.js" />
</Helmet>
</div>
);
}
const App = () => (
<div>
<ComponentWithHeader />
<ComponentWithHeader />
<ComponentWithHeader />
<ComponentWithHeader />
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.