添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Astro 集成 为你的 React 组件实现服务器端渲染和客户端水合。

Astro 包含了一个 astro add 命令,用于自动设置官方集成。如果你愿意,可以改为 手动安装集成

要安装 @astrojs/react ,请在你的项目目录下运行以下命令并根据提示操作:

然后,使用 integrations 属性将此集成应用到你的 astro.config.* 文件中:

astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
// ...
integrations: [react()],
});

要在 Astro 中使用你的第一个 React 组件,请前往我们的 UI 框架文档 。你将了解:

  • 📦 框架组件如何被加载,
  • 💧 客户端水合选项,以及
  • 🤝 有机会将不同的框架混合和嵌套
  • 当你在同一个项目中使用多个 JSX 框架(React、Preact、Solid)时,Astro 需要确定每个组件应该使用哪个 JSX 框架的转换器(transformation)。如果你只向你的项目中添加了一个 JSX 框架集成,那么就不需要额外的配置。

    使用 include (必填)和 exclude (可选)配置选项来指定哪些文件属于哪个框架。为你使用的每个框架提供一个文件或/和文件夹数组。通配符可用于包含多个文件路径。

    我们建议将每个框架的组件放在同一个文件夹中(例如 /components/react/ /components/solid/ ),以便更容易地指定你的包含内容,但这不是必需的:

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import preact from '@astrojs/preact';
    import react from '@astrojs/react';
    import svelte from '@astrojs/svelte';
    import vue from '@astrojs/vue';
    import solid from '@astrojs/solid-js';
    export default defineConfig({
    // 启用多个框架来支持所有不同类型的组件。
    // 如果你只使用一个 JSX 框架,则不需要 `include`!
    integrations: [
    preact({
    include: ['**/preact/*'],
    }),
    react({
    include: ['**/react/*'],
    }),
    solid({
    include: ['**/solid/*'],
    }),
    ],
    });

    从 Astro 组件传递给 React 组件的子元素将被解析为普通字符串,而不是 React 节点。

    例如,下面的 <ReactComponent /> 只会接收一个子元素:

    ---
    import ReactComponent from './ReactComponent';
    ---
    <ReactComponent>
    <div>one</div>
    <div>two</div>
    </ReactComponent>

    如果你正在使用一个 期望 能传递多个子元素的库,例如将某些元素放置在不同的位置,你可能会遇到问题。

    你可以设置实验性标志 experimentalReactChildren ,告诉 Astro 将子元素始终作为 React vnodes 传递给 React。虽然这样做会有一些运行时成本,但有助于保持兼容性。

    你可以在 React 集成的配置中启用此选项:

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import react from '@astrojs/react';
    export default defineConfig({
    // ...
    integrations: [
    react({
    experimentalReactChildren: true,
    }),
    ],
    });