将 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。尽管你可以在线 尝试 React 或使用简单的 HTML 页面,但实际上你想要用于开发的大多数 JavaScript 工具都需要 Node.js。

¥You need to install Node.js for local development. Although you can try React online or with a simple HTML page, realistically most JavaScript tooling you’ll want to use for development requires Node.js.

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

¥Using React for an entire subroute of your existing website

假设你在 example.com 有一个使用另一种服务器技术(如 Rails)构建的现有 Web 应用,并且你想要完全使用 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 部分。

    ¥Build the React part of your app using one of the React-based frameworks.

  2. 在框架配置中指定 /some-app 作为基本路径(具体方法如下:Next.jsGatsby)。

    ¥Specify /some-app as the base path in your framework’s configuration (here’s how: Next.js, Gatsby).

  3. 配置你的服务器或代理,以便 /some-app/ 下的所有请求都由你的 React 应用处理。

    ¥Configure your server or a proxy so that all requests under /some-app/ are handled by your React app.

这确保你的应用的 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 的常用方式 - 事实上,多年来大多数 React 用户都是这样看待 Meta 的!

¥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)。

    ¥Set up a JavaScript environment that lets you use the JSX syntax, split your code into modules with the import / export syntax, and use packages (for example, React) from the npm package registry.

  2. 将 React 组件渲染到页面上你希望看到的位置。

    ¥Render your React components where you want to see them on the page.

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

¥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。

    ¥If your app is already split into files that use import statements, try to use the setup you already have. Check whether writing <div /> in your JS code causes a syntax error. If it causes a syntax error, you might need to transform your JavaScript code with Babel, and enable the Babel React preset to use JSX.

  • 如果你的应用没有用于编译 JavaScript 模块的现有设置,请使用 Vite 进行设置。Vite 社区维护着 许多与后端框架的集成,包括 Rails、Django 和 Laravel。如果你的后端框架未列出,遵循本指南 手动将 Vite 构建与你的后端集成。

    ¥If your app doesn’t have an existing setup for compiling JavaScript modules, set it up with Vite. The Vite community maintains many integrations with backend frameworks, including Rails, Django, and Laravel. If your backend framework is not listed, follow this guide to manually integrate Vite builds with your backend.

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

¥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>);

如果你页面的全部内容都被 “你好世界!” 替换,一切正常!继续阅读。

¥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 屏幕。

¥React Native can also be integrated into existing native apps incrementally. If you have an existing native app for Android (Java or Kotlin) or iOS (Objective-C or Swift), follow this guide to add a React Native screen to it.


React 中文网 - 粤ICP备13048890号