Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(cn): translate content/docs/add-react-to-a-website.md into Chinese #103

Merged
merged 9 commits into from Mar 19, 2019
150 changes: 75 additions & 75 deletions content/docs/add-react-to-a-website.md
Original file line number Diff line number Diff line change
@@ -1,202 +1,202 @@
---
id: add-react-to-a-website
title: Add React to a Website
title: 在网站中添加 React
permalink: docs/add-react-to-a-website.html
redirect_from:
- "docs/add-react-to-an-existing-app.html"
prev: getting-started.html
next: create-a-new-react-app.html
---

Use as little or as much React as you need.
根据需要选择性地使用 React

React has been designed from the start for gradual adoption, and **you can use as little or as much React as you need**. Perhaps you only want to add some "sprinkles of interactivity" to an existing page. React components are a great way to do that.
React 从一开始就被设计为逐步采用,并且**你可以根据需要选择性地使用 React**。可能你只想在现有页面中“局部地添加交互性”。使用 React 组件是一种不错的方式。

The majority of websites aren't, and don't need to be, single-page apps. With **a few lines of code and no build tooling**, try React in a small part of your website. You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.
大多数网站不是、也不需要是单页应用程序。通过**仅仅几行代码并且无需使用构建工具**,试试在你的网站的一小部分中使用 React。然后,你可以逐步扩展它的存在,或只将其涵盖在少数动态部件中。

---

- [Add React in One Minute](#add-react-in-one-minute)
- [Optional: Try React with JSX](#optional-try-react-with-jsx) (no bundler necessary!)
- [一分钟用上 React](#add-react-in-one-minute)
- [可选:使用 React JSX](#optional-try-react-with-jsx) (不需要打包工具!)

## Add React in One Minute {#add-react-in-one-minute}
## 一分钟用上 React {#add-react-in-one-minute}

In this section, we will show how to add a React component to an existing HTML page. You can follow along with your own website, or create an empty HTML file to practice.
在本小节中,我们会展示如何将 React 组件添加到现有的 HTML 页面中。你可以基于自己现有的网站,或创建一个空的 HTML 文件来练习。

There will be no complicated tools or install requirements -- **to complete this section, you only need an internet connection, and a minute of your time.**
不会涉及复杂的工具或安装需求 —— **完成这一节的内容,你只需要连接到网络,以及一分钟的时间。**

Optional: [Download the full example (2KB zipped)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)
可选:[下载完整示例(2KB zipped](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)

### Step 1: Add a DOM Container to the HTML {#step-1-add-a-dom-container-to-the-html}
### 步骤 1: 添加一个 DOM 容器到 HTML {#step-1-add-a-dom-container-to-the-html}

First, open the HTML page you want to edit. Add an empty `<div>` tag to mark the spot where you want to display something with React. For example:
首先,打开你想要编辑的 HTML 页面。添加一个空的 `<div>` 标签作为标记你想要用 React 显示内容的位置。例如:

```html{3}
<!-- ... existing HTML ... -->
<!-- ... 其它 HTML ... -->

<div id="like_button_container"></div>

<!-- ... existing HTML ... -->
<!-- ... 其它 HTML ... -->
```

We gave this `<div>` a unique `id` HTML attribute. This will allow us to find it from the JavaScript code later and display a React component inside of it.
我们给这个 `<div>` 加上唯一的 `id` HTML 属性。这将允许我们稍后用 JavaScript 代码找到它,并在其中显示一个 React 组件。

>Tip
> 提示
>
>You can place a "container" `<div>` like this **anywhere** inside the `<body>` tag. You may have as many independent DOM containers on one page as you need. They are usually empty -- React will replace any existing content inside DOM containers.
> 你可以像这样在 `<body>` 标签内的**任意位置**放置一个“容器” `<div>`。根据需要,你可以在一个页面上放置多个独立的 DOM 容器。它们通常是空标签 —— React 会替换 DOM 容器内的任何已有内容。

### Step 2: Add the Script Tags {#step-2-add-the-script-tags}
### 步骤 2:添加 Script 标签 {#step-2-add-the-script-tags}

Next, add three `<script>` tags to the HTML page right before the closing `</body>` tag:
接下来,在 `</body>` 结束标签之前,向 HTML 页面中添加三个 `<script>` 标签:

```html{5,6,9}
<!-- ... other HTML ... -->
<!-- ... 其它 HTML ... -->

<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<!-- 加载 React-->
<!-- 注意: 部署时,将 "development.js" 替换为 "production.min.js"-->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<!-- Load our React component. -->
<!-- 加载我们的 React 组件。-->
<script src="like_button.js"></script>

</body>
```

The first two tags load React. The third one will load your component code.
前两个标签加载 React。第三个将加载你的组件代码。

### Step 3: Create a React Component {#step-3-create-a-react-component}
### 步骤 3:创建一个 React 组件 {#step-3-create-a-react-component}

Create a file called `like_button.js` next to your HTML page.
在 HTML 页面文件的同级目录下创建一个名为 `like_button.js` 的文件。

Open **[this starter code](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)** and paste it into the file you created.
查看**[这段入门代码](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)**并把它粘贴到你创建的文件中。

>Tip
> 提示
>
>This code defines a React component called `LikeButton`. Don't worry if you don't understand it yet -- we'll cover the building blocks of React later in our [hands-on tutorial](/tutorial/tutorial.html) and [main concepts guide](/docs/hello-world.html). For now, let's just get it showing on the screen!
> 这段代码定义了一个名为 `LikeButton`React 组件。如果你还不明白这段代码的意思,不用担心 —— 我们将在后续的[入门教程](/tutorial/tutorial.html)和[核心概念](/docs/hello-world.html)中介绍 React 的构建块。目前,我们先只做到显示!

After **[the starter code](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)**, add two lines to the bottom of `like_button.js`:
在 `like_button.js` 的底部,在**[入门代码](https://cdn.rawgit.com/gaearon/0b180827c190fe4fd98b4c7f570ea4a8/raw/b9157ce933c79a4559d2aa9ff3372668cce48de7/LikeButton.js)**之后,加入以下两行代码。

```js{3,4}
// ... the starter code you pasted ...
// ... 你粘贴的入门代码 ...

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
```

These two lines of code find the `<div>` we added to our HTML in the first step, and then display our "Like" button React component inside of it.
这两行代码会找到我们在步骤 1 中添加到 HTML 里的 `<div>`,然后在它内部显示我们的 React 组件 “Like” 按钮。

### That's It! {#thats-it}
### 就是这么简单! {#thats-it}

There is no step four. **You have just added the first React component to your website.**
没有第四步了。**你刚刚已经将第一个 React 组件添加到你的网站中。**

Check out the next sections for more tips on integrating React.
查看后续小节,以便查看关于集成 React 的更多提示。

**[View the full example source code](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605)**
**[查看完整的示例源码](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605)**

**[Download the full example (2KB zipped)](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)**
**[下载完整示例(2KB zipped](https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605/archive/f6c882b6ae18bde42dcf6fdb751aae93495a2275.zip)**

### Tip: Reuse a Component {#tip-reuse-a-component}
### 提示:重用一个组件 {#tip-reuse-a-component}

Commonly, you might want to display React components in multiple places on the HTML page. Here is an example that displays the "Like" button three times and passes some data to it:
通常,你可能希望在 HTML 页面的多个位置展示 React 组件。下面是一个示例,它显示了三次 “Like” 按钮,并向各自传入了一些数据:

[View the full example source code](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda)
[查看完整的示例源码](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda)

[Download the full example (2KB zipped)](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda/archive/9d0dd0ee941fea05fd1357502e5aa348abb84c12.zip)
[下载完整示例(2KB zipped](https://gist.github.com/gaearon/faa67b76a6c47adbab04f739cba7ceda/archive/9d0dd0ee941fea05fd1357502e5aa348abb84c12.zip)

>Note
> 注意
>
>This strategy is mostly useful while React-powered parts of the page are isolated from each other. Inside React code, it's easier to use [component composition](/docs/components-and-props.html#composing-components) instead.
> 当页面中以 React 驱动的不同部分是相互独立的时候,这种策略通常非常有用。在 React 代码中,使用[组件组合(component composition](/docs/components-and-props.html#composing-components) 来实现会更容易。

### Tip: Minify JavaScript for Production {#tip-minify-javascript-for-production}
### 提示:为生产环境压缩 JavaScript 代码 {#tip-minify-javascript-for-production}

Before deploying your website to production, be mindful that unminified JavaScript can significantly slow down the page for your users.
在将你的网站部署到生产环境之前,要注意未经压缩的 JavaScript 可能会显著降低用户的访问速度。

If you already minify the application scripts, **your site will be production-ready** if you ensure that the deployed HTML loads the versions of React ending in `production.min.js`:
如果你已经压缩了应用代码,如果你确保已部署的 HTML 加载了以 `production.min.js` 结尾的 React 版本,那么**你的网站是生产就绪(production-ready)的**:

```js
<script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>
```

If you don't have a minification step for your scripts, [here's one way to set it up](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3).
如果你没有一个代码压缩的步骤,[这有一个配置它的方式](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3)

## Optional: Try React with JSX {#optional-try-react-with-jsx}
## 可选:使用 React JSX {#optional-try-react-with-jsx}

In the examples above, we only relied on features that are natively supported by the browsers. This is why we used a JavaScript function call to tell React what to display:
在上面的示例中,我们只依赖了浏览器原生支持的特性。这就是为什么我们使用了 JavaScript 函数调用来告诉 React 要显示什么:

```js
const e = React.createElement;

// Display a "Like" <button>
// 显示一个 "Like" <button>
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
```

However, React also offers an option to use [JSX](/docs/introducing-jsx.html) instead:
但是,React 还提供了一种用 [JSX](/docs/introducing-jsx.html) 来代替实现的选择:

```js
// Display a "Like" <button>
// 显示一个 "Like" <button>
return (
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);
```

These two code snippets are equivalent. While **JSX is [completely optional](/docs/react-without-jsx.html)**, many people find it helpful for writing UI code -- both with React and with other libraries.
这两段代码是等价的。虽然 **JSX [完全是可选的](/docs/react-without-jsx.html)**,但是多数人觉得这样编写 UI 代码更方便 —— 无论是使用 React 还是其它库。

You can play with JSX using [this online converter](https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=Q&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2%2Cstage-3&prettier=true&targets=Node-6.12&version=6.26.0&envVersion=).
你可以用[这个在线转换器](https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=Q&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2%2Cstage-3&prettier=true&targets=Node-6.12&version=6.26.0&envVersion=)来试试 JSX。

### Quickly Try JSX {#quickly-try-jsx}
### 快速尝试 JSX {#quickly-try-jsx}

The quickest way to try JSX in your project is to add this `<script>` tag to your page:
在项目中尝试 JSX 最快的方法是在页面中添加这个 `<script>` 标签:

```html
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
```

Now you can use JSX in any `<script>` tag by adding `type="text/babel"` attribute to it. Here is [an example HTML file with JSX](https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html) that you can download and play with.
现在,你可以在任何 `<script>` 标签内使用 JSX,方法是在为其添加 `type="text/babel"` 属性。这是[一个使用了 JSX 的 HTML 文件的例子](https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html),你可以下载并尝试使用。

This approach is fine for learning and creating simple demos. However, it makes your website slow and **isn't suitable for production**. When you're ready to move forward, remove this new `<script>` tag and the `type="text/babel"` attributes you've added. Instead, in the next section you will set up a JSX preprocessor to convert all your `<script>` tags automatically.
这种方式适合于学习和创建简单的示例。然而,它会使你的网站变慢,并且**不适用于生产环境**。当你准备好更进一步时,删除你添加的这个新的 `<script>` 标签以及`type="text/babel"` 属性。取而代之的,在下一小节中,你将设置一个 JSX 预处理器来自动转换所有 `<script>` 标签的内容。

### Add JSX to a Project {#add-jsx-to-a-project}
### JSX 添加到项目 {#add-jsx-to-a-project}

Adding JSX to a project doesn't require complicated tools like a bundler or a development server. Essentially, adding JSX **is a lot like adding a CSS preprocessor.** The only requirement is to have [Node.js](https://nodejs.org/) installed on your computer.
JSX 添加到项目中并不需要诸如打包工具或开发服务器那样复杂的工具。本质上,添加 JSX **就像添加 CSS 预处理器一样**。唯一的要求是你在计算机上安装了 [Node.js](https://nodejs.org/)

Go to your project folder in the terminal, and paste these two commands:
在终端上跳转到你的项目文件夹,然后粘贴这两个命令:

1. **Step 1:** Run `npm init -y` (if it fails, [here's a fix](https://gist.github.com/gaearon/246f6380610e262f8a648e3e51cad40d))
2. **Step 2:** Run `npm install babel-cli@6 babel-preset-react-app@3`
1. **步骤 1:** 执行 `npm init -y` (如果失败,[这是修复办法](https://gist.github.com/gaearon/246f6380610e262f8a648e3e51cad40d)
2. **步骤 2:** 执行 `npm install babel-cli@6 babel-preset-react-app@3`

>Tip
> 提示
>
>We're **using npm here only to install the JSX preprocessor;** you won't need it for anything else. Both React and the application code can stay as `<script>` tags with no changes.
> 我们**在这里使用 npm 只是用来安装 JSX 预处理器**,之后你不再需要它。React 和应用程序代码都可以继续使用 `<script>` 标签而不做任何更改。

Congratulations! You just added a **production-ready JSX setup** to your project.
恭喜!你刚刚为你的项目加入了一个**生产就绪(production-ready)的 JSX 配置环境**。


### Run JSX Preprocessor {#run-jsx-preprocessor}
### 运行 JSX 预处理器 {#run-jsx-preprocessor}

Create a folder called `src` and run this terminal command:
创建一个名为 `src` 的文件夹并执行这个终端命令:

```
npx babel --watch src --out-dir . --presets react-app/prod
```

>Note
> 注意:
>
>`npx` is not a typo -- it's a [package runner tool that comes with npm 5.2+](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b).
> `npx` 不是拼写错误 —— 它是 [npm 5.2+ 附带的 package 运行工具](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b)
>
>If you see an error message saying "You have mistakenly installed the `babel` package", you might have missed [the previous step](#add-jsx-to-a-project). Perform it in the same folder, and then try again.
> 如果你看到一个错误消息显示为:"You have mistakenly installed the `babel` package",你可能错过了[上一步](#add-jsx-to-a-project)。在同一个文件夹中执行它,然后重试。

Don't wait for it to finish -- this command starts an automated watcher for JSX.
不要等待它运行结束 —— 这个命令启动了一个对 JSX 的自动监听器。

If you now create a file called `src/like_button.js` with this **[JSX starter code](https://cdn.rawgit.com/gaearon/c8e112dc74ac44aac4f673f2c39d19d1/raw/09b951c86c1bf1116af741fa4664511f2f179f0a/like_button.js)**, the watcher will create a preprocessed `like_button.js` with the plain JavaScript code suitable for the browser. When you edit the source file with JSX, the transform will re-run automatically.
如果此时你用这段 **[JSX 入门代码](https://cdn.rawgit.com/gaearon/c8e112dc74ac44aac4f673f2c39d19d1/raw/09b951c86c1bf1116af741fa4664511f2f179f0a/like_button.js)**创建一个 `src/like_button.js` 文件,监听器会创建一个预处理过的 `like_button.js` 文件,它包含了适用于浏览器的普通 JavaScript 代码。当你编辑带有 JSX 的源文件时,转换过程将自动重新执行。

As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called Babel, and you can learn more about it from [its documentation](https://babeljs.io/docs/en/babel-cli/).
这样,在旧浏览器上也能够使用现代 JavaScript 的语法特性,比如 class。我们刚才使用的工具叫 Babel,你可以从[它的文档](https://babeljs.io/docs/en/babel-cli/)中了解更多。

If you notice that you're getting comfortable with build tools and want them to do more for you, [the next section](/docs/create-a-new-react-app.html) describes some of the most popular and approachable toolchains. If not -- those script tags will do just fine!
如果你认为你已经习惯了构建工具,并希望它们能为你做更多事,[下一章节](/docs/create-a-new-react-app.html)描述了一些最流行和易上手的工具链。如果不使用构建工具 —— 直接以 scripts 标签的方式也可以很好地完成工作!