Skip to content

Latest commit

 

History

History
175 lines (141 loc) · 4.95 KB

File metadata and controls

175 lines (141 loc) · 4.95 KB
type title sidebar description githubIntegrationURL category i18nReady
integration
@astrojs/react
label
React
了解如何使用 @astrojs/react 框架集成来扩展 Astro 项目中的组件支持。
renderer
true

import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'

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

安装

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

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

```sh npx astro add react ``` ```sh pnpm astro add react ``` ```sh yarn astro add react ```

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

手动安装

首先,安装 @astrojs/react 包:

```sh npm install @astrojs/react ``` ```sh pnpm add @astrojs/react ``` ```sh yarn add @astrojs/react ```

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

```sh npm install react react-dom ``` ```sh pnpm add react react-dom ``` ```sh yarn add react react-dom ```

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

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

入门指南

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

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

选项

组合多个 JSX 框架

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

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

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

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 虚拟 DOM 节点传递给 React。虽然这样做会有一些运行时成本,但有助于保持兼容性。

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

import { defineConfig } from 'astro/config';
import react from '@astrojs/react';

export default defineConfig({
  // ...
  integrations: [
    react({
      experimentalReactChildren: true,
    }),
  ],
});