内置浏览器 <script> 组件(https://web.nodejs.cn/en-US/docs/Web/HTML/Element/script)让你可以将脚本添加到你的文档中。

🌐 The built-in browser <script> component lets you add a script to your document.

<script> alert("hi!") </script>

参考

🌐 Reference

<script>

要向你的文档添加内联或外部脚本,请渲染内置浏览器 <script> 组件。你可以从任何组件渲染 <script>,并且 React 会在某些情况下将相应的 DOM 元素放置在文档头部,并去重相同的脚本。

🌐 To add inline or external scripts to your document, render the built-in browser <script> component. You can render <script> from any component and React will in certain cases place the corresponding DOM element in the document head and de-duplicate identical scripts.

<script> alert("hi!") </script>
<script src="script.js" />

查看更多示例。

属性

🌐 Props

<script> 支持所有 常用元素属性

它应该有 either childrensrc 属性。

🌐 It should have either children or a src prop.

  • children:一个字符串。内联脚本的源代码。
  • src:一个字符串。外部脚本的 URL。

其他支持的属性:

🌐 Other supported props:

  • async:布尔值。允许浏览器延迟执行脚本,直到文档的其他部分已经被处理——这是为了性能而推荐的行为。
  • crossOrigin:一个字符串。要使用的 CORS 策略。它的可能值是 anonymoususe-credentials
  • fetchPriority:一个字符串。当同时获取多个脚本时,让浏览器按优先级对脚本进行排序。可以是 "high""low""auto"(默认)。
  • integrity:一个字符串。脚本的加密哈希,用于验证其真实性
  • noModule:一个布尔值。在支持 ES 模块的浏览器中禁用脚本——允许为不支持的浏览器提供备用脚本。
  • nonce:一个字符串。在使用严格的内容安全策略时,允许资源的加密随机数
  • referrer:一个字符串。说明在获取脚本及脚本进一步获取的任何资源时应发送的 Referer 头
  • type:一个字符串。说明脚本是经典脚本、ES 模块或导入映射

禁用 React 对脚本的特殊处理的属性:

🌐 Props that disable React’s special treatment of scripts:

  • onError:一个函数。在脚本加载失败时调用。
  • onLoad:一个函数。在脚本加载完成时调用。

不推荐在 React 中使用的属性:

🌐 Props that are not recommended for use with React:

  • blocking:一个字符串。如果设置为 "render",指示浏览器在脚本表加载完之前不要渲染页面。React 使用 Suspense 提供了更精细的控制。
  • defer:一个字符串。在文档加载完成之前,防止浏览器执行脚本。不兼容流式服务器渲染的组件。请改用 async 属性。

特殊渲染行为

🌐 Special rendering behavior

React 可以将 <script> 组件移动到文档的 <head> 并去重相同的脚本。

🌐 React can move <script> components to the document’s <head> and de-duplicate identical scripts.

要选择此行为,请提供 srcasync={true} 属性。如果脚本具有相同的 src,React 将去重这些脚本。async 属性必须为 true,才能安全地移动脚本。

🌐 To opt into this behavior, provide the src and async={true} props. React will de-duplicate scripts if they have the same src. The async prop must be true to allow scripts to be safely moved.

这种特殊处理有两个注意事项:

🌐 This special treatment comes with two caveats:

  • 在脚本渲染之后,React 将忽略对 props 的更改。(如果发生这种情况,React 在开发环境中会发出警告。)
  • 即使渲染它的组件已被卸载,React 也可能将脚本保留在 DOM 中。(这没有任何影响,因为脚本只会在被插入到 DOM 时执行一次。)

用法

🌐 Usage

渲染外部脚本

🌐 Rendering an external script

如果一个组件依赖某些脚本才能正确显示,你可以在组件中渲染一个 <script>。 然而,组件可能在脚本加载完成之前就已经提交。 一旦触发 load 事件,你就可以开始依赖脚本内容,例如通过使用 onLoad 属性。

🌐 If a component depends on certain scripts in order to be displayed correctly, you can render a <script> within the component. However, the component might be committed before the script has finished loading. You can start depending on the script content once the load event is fired e.g. by using the onLoad prop.

React 会对具有相同 src 的脚本进行去重,即使多个组件渲染它,也只将其中一个插入到 DOM 中。

🌐 React will de-duplicate scripts that have the same src, inserting only one of them into the DOM even if multiple components render it.

import ShowRenderedHTML from './ShowRenderedHTML.js';

function Map({lat, long}) {
  return (
    <>
      <script async src="map-api.js" onLoad={() => console.log('script loaded')} />
      <div id="map" data-lat={lat} data-long={long} />
    </>
  );
}

export default function Page() {
  return (
    <ShowRenderedHTML>
      <Map />
    </ShowRenderedHTML>
  );
}

注意

当你想要使用一个脚本时,调用 preinit 函数可能会有好处。调用此函数可能允许浏览器比仅仅渲染 <script> 组件更早地开始获取脚本,例如通过发送 HTTP Early Hints 响应

渲染内联脚本

🌐 Rendering an inline script

要包含内联脚本,请将 <script> 组件渲染为其子元素包含脚本源代码。内联脚本不会去重,也不会移动到文档 <head>

🌐 To include an inline script, render the <script> component with the script source code as its children. Inline scripts are not de-duplicated or moved to the document <head>.

import ShowRenderedHTML from './ShowRenderedHTML.js';

function Tracking() {
  return (
    <script>
      ga('send', 'pageview');
    </script>
  );
}

export default function Page() {
  return (
    <ShowRenderedHTML>
      <h1>My Website</h1>
      <Tracking />
      <p>Welcome</p>
    </ShowRenderedHTML>
  );
}