跳转到内容

@astrojs/ react

这个 Astro 集成 为你的 React 组件启用了服务端渲染和客户端注水。

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

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

终端窗口
npx astro add react

如果你遇到任何问题,请随时在 GitHub 上向我们报告,并尝试下面的手动安装步骤。

首先,安装 @astrojs/react

终端窗口
npm install @astrojs/react

大多数包管理器也会安装相关的对等依赖项。如果你在启动 Astro 时看到 Cannot find package 'react'(或类似)的警告,你需要安装 reactreact-dom 及其类型定义

终端窗口
npm install react react-dom @types/react @types/react-dom

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

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

并将以下代码添加到 tsconfig.json 文件中。

tsconfig.json
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"],
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "react"
}
}

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

  • 📦 框架组件是如何加载的,
  • 💧 客户端注入选项,以及
  • 🤝 混合和嵌套不同框架的机会

当你在同一项目中使用多个 JSX 框架(React、Preact、Solid)时,Astro 需要确定应为每个组件使用哪个 JSX 框架特定的转换。如果你的项目中只添加了一个 JSX 框架集成,则无需额外配置。

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

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

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({
// Enable many frameworks to support all different kinds of components.
// No `include` is needed if you are only using a single JSX framework!
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 虚拟 DOM 节点传递给 React。这会带来一些运行时成本,但有助于提高兼容性。

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

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

默认情况下,Astro 会流式传输 React 组件的输出。但是,你可以通过启用 experimentalDisableStreaming 选项来禁用此行为。这对于支持那些与流式传输不兼容的库(例如某些 CSS-in-JS 解决方案)特别有用。

要为项目中的所有 React 组件禁用流式传输,请将 @astrojs/react 配置为 experimentalDisableStreaming: true

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

更多集成

前端框架

适配器

其他集成

贡献 社区 赞助