简体   繁体   English

反应:如何在同一页面中两次使用相同的组件,但是一次只能加载一个脚本标签

[英]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.

相关问题 vue js在同一页面上多次使用组件 - vue js use component more then one time on the same page 如果第二次只是相同的视频,如何防止相同的视频加载两次 - how to prevent same video loading twice if its just the same video a 2nd time 如何在同一个组件中使用自定义反应查询钩子两次? - How to use custom react query hook twice in the same component? Vue.js在同一页面上两次使用模式组件 - Vuejs use modal component twice on same page 如何基于单击将一个组件中存在的 function 的相同功能用于另一个组件以在 angular 中的两个组件中使用相同的 class 绑定 - How to use same functionalities of function present in one component to another based on click to use same class binding in both components in angular 在一页上渲染两次相同的Google Map - Rendering same Google Map twice on one page HTML 事件同时弹出,如何选择一个 - HTML events pop up in same time, how to just pick one 同一Google Analytics(分析)事件一次触发两次 - Same Google Analytics event fires twice on one call at a same time 使用 JS<script> just in one razor page - Use a JS <script> just in one razor page 如何在同一页面上的多个实例上使用React组件? - How can I use a React component on multiple instances on the same page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM