将 React 添加到现有项目

如果你想为现有项目增加一些交互性,你不必用 React 重写它。将 React 添加到你现有的技术栈中,并在任何地方渲染交互式 React 组件。

🌐 If you want to add some interactivity to your existing project, you don’t have to rewrite it in React. Add React to your existing stack, and render interactive React components anywhere.

注意

你需要安装 Node.js 以进行本地开发。 尽管你可以在线或使用简单的 HTML 页面 尝试 React,但实际上,大多数你想要用于开发的 JavaScript 工具都需要 Node.js。

将 React 用于现有网站的整个子路由

🌐 Using React for an entire subroute of your existing website

假设你有一个现有的 web 应用在 example.com,它是用另一种服务器技术(比如 Rails)构建的,而你想用 React 完全实现所有以 example.com/some-app/ 开头的路由。

🌐 Let’s say you have an existing web app at example.com built with another server technology (like Rails), and you want to implement all routes starting with example.com/some-app/ fully with React.

以下是我们建议的设置方式:

🌐 Here’s how we recommend to set it up:

  1. 构建你应用的 React 部分,使用其中一个 基于 React 的框架
  2. 在你的框架配置中将 /some-app 指定为基础路径(操作方法如下:Next.js, Gatsby)。
  3. 配置你的服务器或代理,以便所有 /some-app/ 下的请求都由你的 React 应用处理。

这确保了你应用中的 React 部分可以从这些框架中内置的最佳实践中受益

🌐 This ensures the React part of your app can benefit from the best practices baked into those frameworks.

许多基于 React 的框架是全栈的,并且可以让你的 React 应用利用服务器的优势。然而,即使你不能或不想在服务器上运行 JavaScript,你也可以使用相同的方法。在这种情况下,在 /some-app/ 提供 HTML/CSS/JS 导出(Next.js 的 next export 输出,Gatsby 的默认输出)即可。

🌐 Many React-based frameworks are full-stack and let your React app take advantage of the server. However, you can use the same approach even if you can’t or don’t want to run JavaScript on the server. In that case, serve the HTML/CSS/JS export (next export output for Next.js, default for Gatsby) at /some-app/ instead.

对现有页面的一部分使用 React

🌐 Using React for a part of your existing page

假设你有一个使用其他技术构建的现有页面(无论是像 Rails 这样的服务器端技术,还是像 Backbone 这样的客户端技术),并且你想在该页面的某个位置渲染交互式 React 组件。这是集成 React 的一种常见方式——实际上,多年来大多数在 Meta 的 React 使用都是这样的!

🌐 Let’s say you have an existing page built with another technology (either a server one like Rails, or a client one like Backbone), and you want to render interactive React components somewhere on that page. That’s a common way to integrate React—in fact, it’s how most React usage looked at Meta for many years!

你可以分两步执行此操作:

🌐 You can do this in two steps:

  1. 搭建一个 JavaScript 环境,让你可以使用 JSX 语法,使用 import / export 语法将代码拆分为模块,并从 npm 包注册表中使用包(例如 React)。
  2. 在页面上你希望看到的位置渲染你的 React 组件

确切的方法取决于你现有的页面设置,所以让我们来看看一些细节。

🌐 The exact approach depends on your existing page setup, so let’s walk through some details.

步骤 1:建立模块化的 JavaScript 环境

🌐 Step 1: Set up a modular JavaScript environment

一个模块化的 JavaScript 环境让你可以将 React 组件写在单独的文件中,而不是将所有代码写在一个文件里。它还允许你使用其他开发者在 npm 注册表上发布的所有优秀包——包括 React 本身!具体如何操作取决于你现有的设置:

🌐 A modular JavaScript environment lets you write your React components in individual files, as opposed to writing all of your code in a single file. It also lets you use all the wonderful packages published by other developers on the npm registry—including React itself! How you do this depends on your existing setup:

  • 如果你的应用已经拆分成使用 import 语句的文件, 尝试使用你已经有的设置。检查在你的 JS 代码中书写 <div /> 是否会导致语法错误。如果它导致语法错误,你可能需要使用 Babel 转换你的 JavaScript 代码,并启用Babel React 预设以使用 JSX。
  • 如果你的应用还没有现成的 JavaScript 模块编译设置, 可以使用 Vite 设置它。Vite 社区维护了 许多与后端框架的集成,包括 Rails、Django 和 Laravel。如果你的后端框架不在列表中,请按照本指南 将 Vite 构建手动集成到你的后端。

要检查你的设置是否有效,请在你的项目文件夹中运行此命令:

🌐 To check whether your setup works, run this command in your project folder:

Terminal
npm install react react-dom

然后在你的主 JavaScript 文件顶部添加这些代码行(它可能叫做 index.jsmain.js):

🌐 Then add these lines of code at the top of your main JavaScript file (it might be called index.js or main.js):

import { createRoot } from 'react-dom/client';

// Clear the existing HTML content
document.body.innerHTML = '<div id="app"></div>';

// Render your React component instead
const root = createRoot(document.getElementById('app'));
root.render(<h1>Hello, world</h1>);

如果你的页面的全部内容被替换成“Hello, world!”的话,一切都正常!继续阅读。

🌐 If the entire content of your page was replaced by a “Hello, world!”, everything worked! Keep reading.

注意

将模块化 JavaScript 环境首次集成到现有项目中可能会让人感到畏惧,但这是值得的!如果遇到困难,可以尝试我们的 社区资源Vite 聊天

🌐 Integrating a modular JavaScript environment into an existing project for the first time can feel intimidating, but it’s worth it! If you get stuck, try our community resources or the Vite Chat.

步骤 2:在页面的任何地方渲染 React 组件

🌐 Step 2: Render React components anywhere on the page

在上一步中,你将此代码放在主文件的顶部:

🌐 In the previous step, you put this code at the top of your main file:

import { createRoot } from 'react-dom/client';

// Clear the existing HTML content
document.body.innerHTML = '<div id="app"></div>';

// Render your React component instead
const root = createRoot(document.getElementById('app'));
root.render(<h1>Hello, world</h1>);

当然,你实际上并不想清除现有的 HTML 内容!

🌐 Of course, you don’t actually want to clear the existing HTML content!

删除此代码。

🌐 Delete this code.

相反,你可能希望在 HTML 的特定位置渲染你的 React 组件。打开你的 HTML 页面(或生成它的服务器模板),并在任何标签上添加一个唯一的 id 属性,例如:

🌐 Instead, you probably want to render your React components in specific places in your HTML. Open your HTML page (or the server templates that generate it) and add a unique id attribute to any tag, for example:

<!-- ... somewhere in your html ... -->
<nav id="navigation"></nav>
<!-- ... more html ... -->

这让你可以使用 document.getElementById 找到该 HTML 元素,并将其传递给 createRoot,以便你可以在其中渲染自己的 React 组件:

🌐 This lets you find that HTML element with document.getElementById and pass it to createRoot so that you can render your own React component inside:

import { createRoot } from 'react-dom/client';

function NavigationBar() {
  // TODO: Actually implement a navigation bar
  return <h1>Hello from React!</h1>;
}

const domNode = document.getElementById('navigation');
const root = createRoot(domNode);
root.render(<NavigationBar />);

注意原始的 index.html HTML 内容是如何被保留下来的,但你自己的 NavigationBar React 组件现在出现在你 HTML 中的 <nav id="navigation"> 内。阅读 createRoot 使用文档 以了解更多关于在现有 HTML 页面中渲染 React 组件的信息。

🌐 Notice how the original HTML content from index.html is preserved, but your own NavigationBar React component now appears inside the <nav id="navigation"> from your HTML. Read the createRoot usage documentation to learn more about rendering React components inside an existing HTML page.

当你在现有项目中采用 React 时,通常会从小的交互组件(比如按钮)开始,然后逐渐“向上扩展”,直到最终整个页面都使用 React 构建。如果你最终达到这个阶段,我们建议之后立即迁移到 一个 React 框架 以充分利用 React 的优势。

🌐 When you adopt React in an existing project, it’s common to start with small interactive components (like buttons), and then gradually keep “moving upwards” until eventually your entire page is built with React. If you ever reach that point, we recommend migrating to a React framework right after to get the most out of React.

在现有的原生移动应用中使用 React Native

🌐 Using React Native in an existing native mobile app

React Native 也可以逐步集成到现有的本地应用中。如果你已经有一个适用于 Android(Java 或 Kotlin)或 iOS(Objective-C 或 Swift)的本地应用,请按照本指南 为其添加一个 React Native 界面。