diff --git a/beta/src/content/learn/importing-and-exporting-components.md b/beta/src/content/learn/importing-and-exporting-components.md index 5aedc2dff..99c974dd0 100644 --- a/beta/src/content/learn/importing-and-exporting-components.md +++ b/beta/src/content/learn/importing-and-exporting-components.md @@ -1,26 +1,26 @@ --- -title: Importing and Exporting Components +title: 導入及導出 Component --- -The magic of components lies in their reusability: you can create components that are composed of other components. But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places. +Component 的神奇之處在於它的可複用性: 你可以創建一個由其他 component 組成的 component。但當你嵌套越來越多 component,則需要開始將它們拆分為不同的檔案。這將會提升檔案的閱讀性,也能讓 component 重複應用在更多地方。 -* What a root component file is -* How to import and export a component -* When to use default and named imports and exports -* How to import and export multiple components from one file -* How to split components into multiple files +* 什麼是根 component 檔案 +* 如何導入以及導出一個 component +* 何時使用預設和具名導入導出 +* 如何從一個檔案導入以及導出多個 component +* 如何將 component 拆分為多個檔案 -## The root component file {/*the-root-component-file*/} +## 根 component 檔案 {/*the-root-component-file*/} -In [Your First Component](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it: +在 [你的第一個 Component](/learn/your-first-component) 中,你創建了一個 `Profile` component,並且 render 在 `Gallery` component 裡: @@ -52,17 +52,17 @@ img { margin: 0 10px 10px 0; height: 90px; } -These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page. +在此範例中,目前所有的 component 都定義在名為 `App.js` 的**根 component 檔案**中。在 [Create React App](https://create-react-app.dev/) 中,你的應用程式應在 `src/App.js` 檔案中定義。根據你的配置,根 component 可能會位於其他檔案中。如果你使用像是 Next.js 這種基於檔案進行路由的框架,那你每個頁面的根 component 都會不一樣。 -## Exporting and importing a component {/*exporting-and-importing-a-component*/} +## 導出以及導入一個 component {/*exporting-and-importing-a-component*/} -What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: +如果將來你想要改變首頁,在此頁面放入科學書籍列表,或者需要將所有的資料移至其他檔案中。將 `Gallery` 以及 `Profile` 移出根 component 檔案會更加合理。這將會使它們更加模組化,並且可以在其他檔案中複用。你可以透過以下三個步驟拆分 component: -1. **Make** a new JS file to put the components in. -2. **Export** your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). -3. **Import** it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports). +1. **創建** 一個新的 JS 檔案來存放該 component +2. **導出** 該檔案中的 component 函式(可以使用 [預設導出](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) 或 [具名導出](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/export#using_named_exports)) +3. 在需要使用該 component 的檔案中**導入**(可以根據相應的導出方式使用 [預設導入](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) 或 [具名導入](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module)) -Here both `Profile` and `Gallery` have been moved out of `App.js` into a new file called `Gallery.js`. Now you can change `App.js` to import `Gallery` from `Gallery.js`: +這裡將 `Profile` 與 `Gallery` 從 `App.js` 檔案中移出,並放入一個名為 `Gallery.js` 的新檔案中。現在,你可以在 `App.js` 導入 `Gallery.js` 中的 `Gallery`: @@ -104,56 +104,56 @@ img { margin: 0 10px 10px 0; height: 90px; } -Notice how this example is broken down into two component files now: +請注意此範例是如何將 component 拆分為兩個檔案: 1. `Gallery.js`: - - Defines the `Profile` component which is only used within the same file and is not exported. - - Exports the `Gallery` component as a **default export.** + - 定義了 `Profile` component,該 component 僅在同個檔案中使用,並沒有被導出。 + - 使用**預設導出**的方式, 導出 `Gallery` component 2. `App.js`: - - Imports `Gallery` as a **default import** from `Gallery.js`. - - Exports the root `App` component as a **default export.** + - 使用**預設導入**的方式,從 `Gallery.js` 導入 `Gallery` + - 使用**預設導出**的方式,導出根 component `App` -You may encounter files that leave off the `.js` file extension like so: +你可能會遇到沒有寫上副檔名 `.js` 的狀況: ```js import Gallery from './Gallery'; ``` -Either `'./Gallery.js'` or `'./Gallery'` will work with React, though the former is closer to how [native ES Modules](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules) work. +不管是 `'./Gallery.js'` 還是 `'./Gallery'` 都可以在 React 中運行,但前者更貼近 [原生 ES 模組](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules)。 -#### Default vs named exports {/*default-vs-named-exports*/} +#### 預設導出 vs 具名導出 {/*default-vs-named-exports*/} -There are two primary ways to export values with JavaScript: default exports and named exports. So far, our examples have only used default exports. But you can use one or both of them in the same file. **A file can have no more than one _default_ export, but it can have as many _named_ exports as you like.** +JavaScript 有兩種主要用來導出值的方式:預設導出以及具名導出。 目前為止,我們的範例只有用到預設導出。但你可以在同一個檔案中,選擇使用其中一種,或者兩種都使用。**一個檔案中僅能有一個預設導出,但可以有多個具名導出**。 -![Default and named exports](/images/docs/illustrations/i_import-export.svg) +![預設導出以及具名導出](/images/docs/illustrations/i_import-export.svg) -How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track: +Component 的導出方式決定了其導入方式。當你試著用預設導入,導入具名導出的 component 時將會報錯!下方圖表可以幫助你更好地理解它們: -| Syntax | Export statement | Import statement | +| 語法 | 導出陳述 | 導入陳述 | | ----------- | ----------- | ----------- | -| Default | `export default function Button() {}` | `import Button from './button.js';` | -| Named | `export function Button() {}` | `import { Button } from './button.js';` | +| 預設 | `export default function Button() {}` | `import Button from './button.js';` | +| 具名 | `export function Button() {}` | `import { Button } from './button.js';` | -When you write a _default_ import, you can put any name you want after `import`. For example, you could write `import Banana from './button.js'` instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That's why they are called _named_ imports! +當使用預設導入時,你可以在 `import` 後使用任意命名。例如 `import Banana from './button.js'`,你仍舊可以獲取一致的預設導出內容。相反地,對於具名導入,導入與導出的名稱必須一致。這也是為什麼它們被稱為 _具名_ 導入! -**People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.** Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like `export default () => {}`, are discouraged because they make debugging harder. +**當檔案中只需要導出一個 component 時,人們通常會使用預設導出,當檔案包含多個 component 或值需要導出時,則會使用具名導出**。無論你偏好哪種方式,請記得給予 component 以及對應檔案一個有意義的命名。不建議使用未命名的 component,像是 `export default () => {}`,這將導致除錯變得困難。 -## Exporting and importing multiple components from the same file {/*exporting-and-importing-multiple-components-from-the-same-file*/} +## 從同一檔案導出及導入多個 component {/*exporting-and-importing-multiple-components-from-the-same-file*/} -What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a *default* export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a *named* export for `Profile`. **A file can only have one default export, but it can have numerous named exports!** +如果你只想要展示一個 `Profile`,而非整個圖集。你也可以導出 `Profile` component。但是 `Gallery.js` 已經包含 *預設* 導出,你不能 _兩個_ 預設導出。你可以創建一個新檔案以進行預設導出,或是你可以將 `Profile` 進行 *具名* 導出。**同一檔案只能有一個預設導出,但可以有多個具名導出!** -> To reduce the potential confusion between default and named exports, some teams choose to only stick to one style (default or named), or avoid mixing them in a single file. It's a matter of preference. Do what works best for you! +> 為了減少預設導出和具名導出之間的混淆,有些團隊會選擇只使用其中一種風格(預設或具名),或者避免在同一個檔案中混合使用。這因人而異,選擇最適合你的即可! -First, **export** `Profile` from `Gallery.js` using a named export (no `default` keyword): +首先,使用具名導出的方式,將 `Profile` 從 `Gallery.js` **導出**(不使用 `default` 關鍵字): ```js export function Profile() { @@ -161,13 +161,13 @@ export function Profile() { } ``` -Then, **import** `Profile` from `Gallery.js` to `App.js` using a named import (with the curly braces): +接著,使用具名導入的方式,從 `Gallery.js` **導入** `Profile` 至 `App.js`(使用大括號): ```js import { Profile } from './Gallery.js'; ``` -Finally, **render** `` from the `App` component: +最後,在 `App` component 中 **render** ``: ```js export default function App() { @@ -175,7 +175,7 @@ export default function App() { } ``` -Now `Gallery.js` contains two exports: a default `Gallery` export, and a named `Profile` export. `App.js` imports both of them. Try editing `` to `` and back in this example: +現在 `Gallery.js` 包含兩個導出:一個是預設導出的 `Gallery`,一個是具名導出的 `Profile`。`App.js` 均導入了它們。請試著將下方範例中的 `` 改為 ``: @@ -218,24 +218,25 @@ img { margin: 0 10px 10px 0; height: 90px; } -Now you're using a mix of default and named exports: +現在,你混合使用了預設導出以及具名導出: * `Gallery.js`: - - Exports the `Profile` component as a **named export called `Profile`.** - - Exports the `Gallery` component as a **default export.** + - 使用 **具名導出** 的方式,導出 `Profile` component,並命名為 `Profile`。 + - 使用 **預設導出** 的方式,導出 `Gallery` component。 * `App.js`: - - Imports `Profile` as a **named import called `Profile`** from `Gallery.js`. - - Imports `Gallery` as a **default import** from `Gallery.js`. - - Exports the root `App` component as a **default export.** + - 使用 **具名導入** 的方式,從 `Gallery.js` 導入 `Profile`,並命名為 `Profile`。 + - 使用 **預設導入** 的方式,從 `Gallery.js` 導入 `Gallery`。 + - 使用 **預設導出** 的方式,導出根 component `App`。 -On this page you learned: +在本章節中,你學到了: -* What a root component file is -* How to import and export a component -* When and how to use default and named imports and exports -* How to export multiple components from the same file +* 什麼是根 component 檔案 +* 如何導入以及導出一個 component +* 何時使用預設和具名導入導出 +* 如何從一個檔案導入以及導出多個 component +* 如何將 component 拆分為多個檔案 @@ -243,22 +244,22 @@ On this page you learned: -#### Split the components further {/*split-the-components-further*/} +#### 進一步拆分 component {/*split-the-components-further*/} -Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing. +現在,`Gallery.js` 同時導出了 `Profile` 與 `Gallery`,這會讓人感到有些混淆。 -Move the `Profile` component to its own `Profile.js`, and then change the `App` component to render both `` and `` one after another. +試著將 `Profile` component 移至 `Profile.js`,然後更新 `App` component,依序 render `` 與 ``。 -You may use either a default or a named export for `Profile`, but make sure that you use the corresponding import syntax in both `App.js` and `Gallery.js`! You can refer to the table from the deep dive above: +你可能會使用預設導出或具名導出的方式來導出 `Profile`,但請確保在 `App.js` 與 `Gallery.js` 中使用了相對應的導入語法!具體方法可參考下方表格: -| Syntax | Export statement | Import statement | +| 語法 | 導出陳述 | 導入陳述 | | ----------- | ----------- | ----------- | -| Default | `export default function Button() {}` | `import Button from './button.js';` | -| Named | `export function Button() {}` | `import { Button } from './button.js';` | +| 預設 | `export default function Button() {}` | `import Button from './button.js';` | +| 具名 | `export function Button() {}` | `import { Button } from './button.js';` | -Don't forget to import your components where they are called. Doesn't `Gallery` use `Profile`, too? +別忘了在呼叫它們的地方導入你的 component,因為 `Gallery` 也會使用到 `Profile`。 @@ -309,11 +310,11 @@ img { margin: 0 10px 10px 0; height: 90px; } -After you get it working with one kind of exports, make it work with the other kind. +當你成功使用其中一種導出方式時,請嘗試使用另一種方法實現。 -This is the solution with named exports: +具名導出的解決方法: @@ -363,7 +364,7 @@ img { margin: 0 10px 10px 0; height: 90px; } -This is the solution with default exports: +預設導出的解決方法: diff --git a/beta/src/content/learn/writing-markup-with-jsx.md b/beta/src/content/learn/writing-markup-with-jsx.md index 335f192af..fdc1e45be 100644 --- a/beta/src/content/learn/writing-markup-with-jsx.md +++ b/beta/src/content/learn/writing-markup-with-jsx.md @@ -1,24 +1,24 @@ --- -title: Writing Markup with JSX +title: 用 JSX 撰寫 Markup --- -*JSX* is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it. +*JSX* 是一種 JavaScript 的擴充語法,讓你能夠在 JavaScript 檔案中編寫類似 HTML 的 markup。雖然也可以使用其他的方式來編寫 component,但大多數的 React 開發者偏好於使用簡明的 JSX,並在大部分代碼庫中使用它。 -* Why React mixes markup with rendering logic -* How JSX is different from HTML -* How to display information with JSX +* 為什麼 React 耦合 markup 與 render 邏輯 +* JSX 與 HTML 有什麼區別 +* 如何透過 JSX 展示資訊 -## JSX: Putting markup into JavaScript {/*jsx-putting-markup-into-javascript*/} +## JSX:將 markup 引入 JavaScript {/*jsx-putting-markup-into-javascript*/} -The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page's logic lived separately in JavaScript: +網頁是建構於 HTML、CSS 與 JavaScript 之上的。多年以來,網頁開發者將內容存放在 HTML,在 CSS 中設計樣式,然後將邏輯存放於 JavaScript 中-通常是在不同的文件中!頁面內容透過標記式語言存放於 HTML 檔案中,而邏輯則單獨存放在 JavaScript 檔案中: @@ -36,7 +36,7 @@ JavaScript -But as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why **in React, rendering logic and markup live together in the same place—components.** +但隨著網頁的交互性越來越強,邏輯增加了對內容的決定性。JavaScript 負責了 HTML 的內容! 這也是為什麼**在 React 中,render 邏輯與 markup 存在於同一個地方-component**。 @@ -54,19 +54,19 @@ But as the Web became more interactive, logic increasingly determined content. J -Keeping a button's rendering logic and markup together ensures that they stay in sync with each other on every edit. Conversely, details that are unrelated, such as the button's markup and a sidebar's markup, are isolated from each other, making it safer to change either of them on their own. +將一個按鈕的 render 邏輯與 markup 放在一起,可以確保它們在每次編輯時都能互相保持同步。反之,彼此無關的細節則是互相隔離的,像是按鈕的 markup 與側邊欄的 markup。這樣可以使修改其中一方時更加安全。 -Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. The best way to understand this is to convert some HTML markup to JSX markup. +每個 React component 都是一個 JavaScript 函式,裡面可能會包含一些用於瀏覽器 render 的 markup。 React component 使用名為 JSX 的擴充語法來表示 markup。JSX 看起來像是 HTML,但它的語法較為嚴格,並且可以展示動態資訊。了解這些區別的最好方式就是將一些 HTML markup 轉換為 JSX markup。 -JSX and React are two separate things. They're often used together, but you *can* [use them independently](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform) of each other. JSX is a syntax extension, while React is a JavaScript library. +JSX 與 React 是互相獨立的東西,它們經常一起被使用,但你 *可以* [單獨地使用它們](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform)。JSX 是一種擴充語法,React 則是一個 JavaScript 函式庫。 -## Converting HTML to JSX {/*converting-html-to-jsx*/} +## 將 HTML 轉換為 JSX {/*converting-html-to-jsx*/} -Suppose that you have some (perfectly valid) HTML: +假設你有一些 (完全有效的) HTML: ```html

Hedy Lamarr's Todos

@@ -82,7 +82,7 @@ Suppose that you have some (perfectly valid) HTML: ``` -And you want to put it into your component: +然後你想要將它放入你的 component: ```js export default function TodoList() { @@ -92,7 +92,7 @@ export default function TodoList() { } ``` -If you copy and paste it as is, it will not work: +如果像下方這樣直接複製貼上是沒有辦法運作的: @@ -122,21 +122,21 @@ img { height: 90px } -This is because JSX is stricter and has a few more rules than HTML! If you read the error messages above, they'll guide you to fix the markup, or you can follow the guide below. +這是因為 JSX 比語法 HTML 更加嚴格,且有更多的規則!上方的錯誤訊息可以幫助你修復 markup,或是你也可以參考下方的指引。 -Most of the times, React's on-screen error messages will help you find where the problem is. Give them a read if you get stuck! +大多數情況下,React 在屏幕上的錯誤訊息可以幫助你找到問題所在,如果在編寫過程中遇到問題就參考一下它們吧! -## The Rules of JSX {/*the-rules-of-jsx*/} +## JSX 的規則 {/*the-rules-of-jsx*/} -### 1. Return a single root element {/*1-return-a-single-root-element*/} +### 1. 回傳單一根元素 {/*1-return-a-single-root-element*/} -To return multiple elements from a component, **wrap them with a single parent tag.** +如果想要在一個 component 中回傳多個元素,**請將它們包裹進父標籤**。 -For example, you can use a `
`: +例如,你可以使用一個 `
` 標籤: ```js {1,11}
@@ -153,7 +153,7 @@ For example, you can use a `
`: ``` -If you don't want to add an extra `
` to your markup, you can write `<>` and `` instead: +如果你不想要在你的 markup 放入多餘的 `
` 標籤,可以改為使用 `<>` 與 ``: ```js {1,11} <> @@ -169,21 +169,21 @@ If you don't want to add an extra `
` to your markup, you can write `<>` and ``` -This empty tag is called a *[Fragment.](/reference/react/Fragment)* Fragments let you group things without leaving any trace in the browser HTML tree. +這個空標籤稱為 *[Fragment](/reference/react/Fragment)*,Fragment 允許你將元素集合在一起,且不會在 HTML 中產生額外節點。 -#### Why do multiple JSX tags need to be wrapped? {/*why-do-multiple-jsx-tags-need-to-be-wrapped*/} +#### 為什麼多個 JSX 標籤需要被包裹起來? {/*why-do-multiple-jsx-tags-need-to-be-wrapped*/} -JSX looks like HTML, but under the hood it is transformed into plain JavaScript objects. You can't return two objects from a function without wrapping them into an array. This explains why you also can't return two JSX tags without wrapping them into another tag or a Fragment. +JSX 看起來與 HTML 非常相似,但它實際上是 JavaScript 物件。你不能在沒有使用 array 包裹它們的情況下,在一個函式裡回傳兩個物件。這解釋了為什麼你不能在沒有使用其他標籤或 Fragment 包裹的情況下回傳兩個 JSX 標籤。 -### 2. Close all the tags {/*2-close-all-the-tags*/} +### 2. 閉合所有標籤 {/*2-close-all-the-tags*/} -JSX requires tags to be explicitly closed: self-closing tags like `` must become ``, and wrapping tags like `
  • oranges` must be written as `
  • oranges
  • `. +JSX 標籤需要明確地閉合:如果是自閉標籤,像是 ``,則需要改為 ``,而像 `
  • oranges` 這樣只有開始標籤的元素則需改為 `
  • oranges
  • `。 -This is how Hedy Lamarr's image and list items look closed: +海蒂・拉瑪的照片與列表項目更改後如下: ```js {2-6,8-10} <> @@ -200,11 +200,11 @@ This is how Hedy Lamarr's image and list items look closed: ``` -### 3. camelCase all most of the things! {/*3-camelcase-salls-most-of-the-things*/} +### 3. 全部 大部分使用駝峰式命名! {/*3-camelcase-salls-most-of-the-things*/} -JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can't contain dashes or be reserved words like `class`. +JSX 最終會被轉化為 JavaScript,編寫在 JSX 中的屬性會變成 JavaScript 物件中的 key。在你的 component 中,你會經常需要使用變數的方式讀取這些屬性。但是 JavaScript 對變數命名有限制。例如,它們的名字不能包含連字號,或者是使用像是 `class` 這樣的保留字。 -This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of `stroke-width` you use `strokeWidth`. Since `class` is a reserved word, in React you write `className` instead, named after the [corresponding DOM property](https://developer.mozilla.org/en-US/docs/Web/API/Element/className): +這就為什麼在 React 中,許多 HTML 與 SVG 屬性都使用駝峰式命名法。例如,將 `stroke-width` 改為 `strokeWidth`。由於 `class` 為保留字,因此在 React 中需要改為使用 `className` 來替代。 這也是依據 [相應的 DOM 屬性](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) 命名: ```js {4} ``` -You can [find all these attributes in the list of DOM component props.](/reference/react-dom/components/common) If you get one wrong, don't worry—React will print a message with a possible correction to the [browser console.](https://developer.mozilla.org/docs/Tools/Browser_Console) +你可以 [在 DOM component props 列表找到所有屬性](/reference/react-dom/components/common),如果你在過程中發生了錯誤,別擔心-React 會在 [瀏覽器控制台](https://developer.mozilla.org/docs/Tools/Browser_Console) 打印出可能的更正信息。 -For historical reasons, [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) and [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) attributes are written as in HTML with dashes. +由於歷史原因,[`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) 與 [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) 屬性的寫法與 HTML 相同,同樣使用連字號。 -### Pro-tip: Use a JSX Converter {/*pro-tip-use-a-jsx-converter*/} +### 專業提醒:使用 JSX 轉換器 {/*pro-tip-use-a-jsx-converter*/} -Converting all these attributes in existing markup can be tedious! We recommend using a [converter](https://transform.tools/html-to-jsx) to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it's still worth understanding what is going on so that you can comfortably write JSX on your own. +轉換所有現有的 markup 屬性是一件繁瑣的事情!我們建議使用 [轉換器](https://transform.tools/html-to-jsx) 來將現有 HTML 與 SVG 轉換為 JSX。轉換器在實務上是非常實用的,但我們仍有必要去理解轉換過程,這樣你就可以編寫自己的 JSX 了。 -Here is your final result: +以下為最終結果: @@ -258,11 +258,11 @@ img { height: 90px } -Now you know why JSX exists and how to use it in components: +現在,你知道為什麼我們需要 JSX,並且知道如何在 component 中使用它: -* React components group rendering logic together with markup because they are related. -* JSX is similar to HTML, with a few differences. You can use a [converter](https://transform.tools/html-to-jsx) if you need to. -* Error messages will often point you in the right direction to fixing your markup. +* 由於 render 邏輯與 markup 關係緊閉,所以 React 將它們存放在同一個 component 中。 +* JSX 與 HTML 非常相似,但它們有些許不同,如果你需要轉換它們,你可以使用 [轉換器](https://transform.tools/html-to-jsx)。 +* 錯誤提示訊息通常能指引你往正確的方向修復 markup。 @@ -270,9 +270,9 @@ Now you know why JSX exists and how to use it in components: -#### Convert some HTML to JSX {/*convert-some-html-to-jsx*/} +#### 將 HTML 轉換為 JSX {/*convert-some-html-to-jsx*/} -This HTML was pasted into a component, but it's not valid JSX. Fix it: +下方的 HTML 是直接被複製到 component 中的,並非有效的 JSX。請試著修復它: @@ -308,7 +308,7 @@ export default function Bio() { -Whether to do it by hand or using the converter is up to you! +手動修復或是使用轉換器都可以的,一切取決於你! diff --git a/beta/src/content/learn/your-first-component.md b/beta/src/content/learn/your-first-component.md index 0cb88bbb1..82cf53dd1 100644 --- a/beta/src/content/learn/your-first-component.md +++ b/beta/src/content/learn/your-first-component.md @@ -1,24 +1,24 @@ --- -title: Your First Component +title: 你的第一個 Component --- -*Components* are one of the core concepts of React. They are the foundation upon which you build user interfaces (UI), which makes them the perfect place to start your React journey! +*Component* 是 React 的核心概念之一,它們是建構使用者介面 (UI) 的基礎,是你踏上 React 旅程的完美開端! -* What a component is -* What role components play in a React application -* How to write your first React component +* 什麼是 Component +* Component 在 React 中扮演了什麼角色 +* 如何編寫你的第一個 React Component -## Components: UI building blocks {/*components-ui-building-blocks*/} +## Component:建構 UI 的模塊 {/*components-ui-building-blocks*/} -On the Web, HTML lets us create rich structured documents with its built-in set of tags like `

    ` and `
  • `: +在網頁中,HTML 允許我們透過使用內建標籤來創建富有結構的文檔,像是 `

    ` 與 `
  • `: ```html
    @@ -31,11 +31,11 @@ On the Web, HTML lets us create rich structured documents with its built-in set
    ``` -This markup represents this article `
    `, its heading `

    `, and an (abbreviated) table of contents as an ordered list `
      `. Markup like this, combined with CSS for style, and JavaScript for interactivity, lies behind every sidebar, avatar, modal, dropdown—every piece of UI you see on the Web. +此 markup 以 `
      ` 來表示文章,以 `

      ` 來表示它的標題, 並且使用 `
        ` 來表示有序的(縮寫)列表內容,這些 markup 結合了 CSS 樣式,以及使用 JavaScript 展現互動性,每一個側邊欄、頭像、互動視窗的背後都是這麼運作的-你在網頁上所看到的每一個 UI 模組。 -React lets you combine your markup, CSS, and JavaScript into custom "components", **reusable UI elements for your app.** The table of contents code you saw above could be turned into a `` component you could render on every page. Under the hood, it still uses the same HTML tags like `
        `, `

        `, etc. +React 允許你將 markup、CSS 以及 JavaScript 結合為自定義「component」, **即應用程式中可複用的 UI 元素**。上文中的程式碼可以改寫為一個能夠 render 在各個頁面上的 `` component,實際上,使用的依舊是 `
        `、`

        ` 等相同的標籤。 -Just like with HTML tags, you can compose, order and nest components to design whole pages. For example, the documentation page you're reading is made out of React components: +就像是 HTML 標籤一樣,你可以編寫、排序以及使用嵌套結構來設計整個頁面。例如,你正在看閱讀的文檔頁面就是由 React component 所組成: ```js @@ -51,11 +51,11 @@ Just like with HTML tags, you can compose, order and nest components to design w ``` -As your project grows, you will notice that many of your designs can be composed by reusing components you already wrote, speeding up your development. Our table of contents above could be added to any screen with ``! You can even jumpstart your project with the thousands of components shared by the React open source community like [Chakra UI](https://chakra-ui.com/) and [Material UI.](https://material-ui.com/) +隨著專案的成長,你會發現有許多設計可以透過複用已經完成的 component 來實現,進而加速你的開發時程。上文所提到的列表內容,可以透過 `` component 添加到任意頁面中!你甚至可以使用 React 開源社群(例如 [Chakra UI](https://chakra-ui.com/) 與 [Material UI](https://material-ui.com/))所分享的大量 component 來快速啟動開發。 -## Defining a component {/*defining-a-component*/} +## 定義 component {/*defining-a-component*/} -Traditionally when creating web pages, web developers marked up their content and then added interaction by sprinkling on some JavaScript. This worked great when interaction was a nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity first while still using the same technology: **a React component is a JavaScript function that you can _sprinkle with markup_.** Here's what that looks like (you can edit the example below): +傳統網頁開發時,網頁開發者會使用標記式語言來描述內容,然後透過 JavaScript 來實現互動,這種方式展現了良好的網頁互動。現今許多的網頁與應用程式都需具有互動性。React 將互動性視為重要指標,並且使用了相同的技術:**React component 是一個可以使用 markup 進行擴展的 JavaScript 函式**,如下所示(你可以編輯下方的範例): @@ -76,33 +76,33 @@ img { height: 200px; } -And here's how to build a component: +以下為建構 component 的方法: -### Step 1: Export the component {/*step-1-export-the-component*/} +### 第一步: 導出 component {/*step-1-export-the-component*/} -The `export default` prefix is a [standard JavaScript syntax](https://developer.mozilla.org/docs/web/javascript/reference/statements/export) (not specific to React). It lets you mark the main function in a file so that you can later import it from other files. (More on importing in [Importing and Exporting Components](/learn/importing-and-exporting-components)!) +`export default` 前綴是一種 [JavaScript 標準語法](https://developer.mozilla.org/zh-TW/docs/web/javascript/reference/statements/export) (並非 React 特性)。它允許你標記檔案中的主要函式,以便你之後可以在其他檔案導入它。(更多導入內容請參閱 [導入及導出 Component](/learn/importing-and-exporting-components) !) -### Step 2: Define the function {/*step-2-define-the-function*/} +### 第二步:定義函式 {/*step-2-define-the-function*/} -With `function Profile() { }` you define a JavaScript function with the name `Profile`. +透過 `function Profile() { }` 定義名為 `Profile` 的 JavaScript 函式。 -React components are regular JavaScript functions, but **their names must start with a capital letter** or they won't work! +React component 為常規的 JavaScript 函式,但**它們的名稱必須以大寫字母為開頭**,否則將無法運行! -### Step 3: Add markup {/*step-3-add-markup*/} +### 第三步:添加 markup {/*step-3-add-markup*/} -The component returns an `` tag with `src` and `alt` attributes. `` is written like HTML, but it is actually JavaScript under the hood! This syntax is called [JSX](/learn/writing-markup-with-jsx), and it lets you embed markup inside JavaScript. +component 會回傳一個帶有 `src` 與 `alt` 屬性的 `` 標籤。`` 寫得像 HTML,但它實際上是 JavaScript!這種語法被稱為 [JSX](/learn/writing-markup-with-jsx),它允許你在 JavaScript 中嵌入 markup。 -Return statements can be written all on one line, as in this component: +回傳的內容可以全寫在同一行,如下方 component: ```js return Katherine Johnson; ``` -But if your markup isn't all on the same line as the `return` keyword, you must wrap it in a pair of parentheses like this: +但是,如果你的 markup 與 `return` 關鍵字不在同一行,則必須使將它們包裹在一對括號中,如下所示: ```js return ( @@ -114,13 +114,13 @@ return ( -Without parentheses, any code on the lines after `return` [will be ignored](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)! +沒有使用括號包裹的話,任何在 `return` 下一行的程式碼都 [將被忽略](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)! -## Using a component {/*using-a-component*/} +## 使用 component {/*using-a-component*/} -Now that you've defined your `Profile` component, you can nest it inside other components. For example, you can export a `Gallery` component that uses multiple `Profile` components: +現在,你已經定義了 `Profile` component,你可以將它們嵌套進其他的 component 中。舉例來說,你可以導出一個包含多個 `Profile` component 的 `Gallery` component: @@ -152,14 +152,14 @@ img { margin: 0 10px 10px 0; height: 90px; } -### What the browser sees {/*what-the-browser-sees*/} +### 瀏覽器所看到的 {/*what-the-browser-sees*/} -Notice the difference in casing: +注意下方兩者的區別: -* `
        ` is lowercase, so React knows we refer to an HTML tag. -* `` starts with a capital `P`, so React knows that we want to use our component called `Profile`. +* `
        ` 是小寫的,所以 React 知道我們指的是 HTML 標籤。 +* `` 的開頭為大寫字母 `P`,所以 React 知道我們想要使用的是名為 `Profile` 的 component。 -And `Profile` contains even more HTML: ``. In the end, this is what the browser sees: +`Profile` 包含了更多 HTML:``。瀏覽器最後看見的內容會是這樣: ```html
        @@ -170,15 +170,15 @@ And `Profile` contains even more HTML: ``. In the end, this is what the b
        ``` -### Nesting and organizing components {/*nesting-and-organizing-components*/} +### 嵌套與組織 component {/*nesting-and-organizing-components*/} -Components are regular JavaScript functions, so you can keep multiple components in the same file. This is convenient when components are relatively small or tightly related to each other. If this file gets crowded, you can always move `Profile` to a separate file. You will learn how to do this shortly on the [page about imports.](/learn/importing-and-exporting-components) +Component 為常規的 JavaScript 函式,所以你可以將多個 component 放在同一個檔案中。這在 component 相對較小或是彼此關係緊密時是非常方便的。如果檔案變得過於擁擠,你可以隨時將 `Profile` 移至不同的檔案。你可以立即在 [導入相關章節](/learn/importing-and-exporting-components) 學習如何做到這些。 -Because the `Profile` components are rendered inside `Gallery`—even several times!—we can say that `Gallery` is a **parent component,** rendering each `Profile` as a "child". This is part of the magic of React: you can define a component once, and then use it in as many places and as many times as you like. +由於 `Profile` component 在 `Gallery` 中被 render-甚至數次!-我們可以將 `Gallery` 稱為 **parent component**,將每個 `Profile` 視為「child」render。這是 React 神奇所在之一,你可以透過定義 component 一次,然後根據需求在多個地方多次使用。 -Components can render other components, but **you must never nest their definitions:** +Component 可以 render 其他的 component,但是**請不要嵌套它們的定義:** ```js {2-5} export default function Gallery() { @@ -190,7 +190,7 @@ export default function Gallery() { } ``` -The snippet above is [very slow and causes bugs.](/learn/preserving-and-resetting-state#different-components-at-the-same-position-reset-state) Instead, define every component at the top level: +上方這段程式碼[非常慢,並且將導致 bug 的發生](/learn/preserving-and-resetting-state#different-components-at-the-same-position-reset-state)。因此,你應該在頂層定義每個 component: ```js {5-8} export default function Gallery() { @@ -203,34 +203,34 @@ function Profile() { } ``` -When a child component needs some data from a parent, [pass it by props](/learn/passing-props-to-a-component) instead of nesting definitions. +當 child component 需要獲取 parent 的數據,你需要 [透過 props 傳遞](/learn/passing-props-to-a-component),而不是嵌套定義。 -#### Components all the way down {/*components-all-the-way-down*/} +#### 萬物皆是 component {/*components-all-the-way-down*/} -Your React application begins at a "root" component. Usually, it is created automatically when you start a new project. For example, if you use [CodeSandbox](https://codesandbox.io/) or [Create React App](https://create-react-app.dev/), the root component is defined in `src/App.js`. If you use the framework [Next.js](https://nextjs.org/), the root component is defined in `pages/index.js`. In these examples, you've been exporting root components. +你的 React 應用程式從「根」component 開始。通常,它會在你啟動新專案時自動創建。 舉例來說,如果使用 [CodeSandbox](https://codesandbox.io/) 或 [Create React App](https://create-react-app.dev/),根 component 會被定義在 `src/App.js`。如果你是使用 [Next.js](https://nextjs.org/) 框架,根 component 則會被定義在 `pages/index.js`。在這些例子當中,你已經導出了根 component。 -Most React apps use components all the way down. This means that you won't only use components for reusable pieces like buttons, but also for larger pieces like sidebars, lists, and ultimately, complete pages! Components are a handy way to organize UI code and markup, even if some of them are only used once. +大多數 React 應用程式只有 component。這意味著你不僅可以將 component 用於具有複用性的部分,例如按鈕,還可以用於更大規模的地方,像是側邊欄、列表以及完成最終的完整頁面!Component 是組織 UI 程式碼與 markup 的一種便捷方式,即便部分的 component 只使用了一次。 -Frameworks like Next.js take this a step further. Instead of using an empty HTML file and letting React "take over" managing the page with JavaScript, they *also* generate the HTML automatically from your React components. This allows your app to show some content before the JavaScript code loads. +像是 Next.js 這樣的框架會做更多事情,與使用空白 HTML 檔案並且讓 React 使用 JavaScript「接手」管理頁面不同,它們 *還會* 根據你的 React component 自動生成 HTML。這使得你的應用程式可以在 JavaScript 載入之前就顯示部分內容。 -Still, many websites only use React to [add "sprinkles of interactivity".](/learn/add-react-to-a-website) They have many root components instead of a single one for the entire page. You can use as much—or as little—React as you need. +儘管如此,許多網站僅使用 React 來[增添「互動性」](/learn/add-react-to-a-website),它們有許多根 component,而不是整個頁面中的單個 component。你可以根據需求盡可能多或盡可能少地使用 React。 -You've just gotten your first taste of React! Let's recap some key points. +你剛剛第一次體驗了 React!讓我們來回顧一些重點。 -* React lets you create components, **reusable UI elements for your app.** -* In a React app, every piece of UI is a component. -* React components are regular JavaScript functions except: +* React 允許你創建 component,**應用程式中可複用的 UI 元素**。 +* 在 React 應用程式中,所有的 UI 模塊都是一個 component。 +* React component 是常規的 JavaScript 函式,除了: - 1. Their names always begin with a capital letter. - 2. They return JSX markup. + 1. 它們的名字總是以大寫字母為開頭。 + 2. 它們回傳 JSX markup。 @@ -238,9 +238,9 @@ You've just gotten your first taste of React! Let's recap some key points. -#### Export the component {/*export-the-component*/} +#### 導出 component {/*export-the-component*/} -This sandbox doesn't work because the root component is not exported: +由於根 component 沒有被導出,導致這個沙盒無法運作: @@ -261,11 +261,11 @@ img { height: 181px; } -Try to fix it yourself before looking at the solution! +請試著在查閱解答前自行修復它! -Add `export default` before the function definition like so: +在函式定義前加上 `export default`,如下所示: @@ -286,17 +286,17 @@ img { height: 181px; } -You might be wondering why writing `export` alone is not enough to fix this example. You can learn the difference between `export` and `export default` in [Importing and Exporting Components.](/learn/importing-and-exporting-components) +你可能會想知道,為什麼單獨寫 `export` 時不足以修復這個問題。你可以在 [導入與導出 Component](/learn/importing-and-exporting-components) 中了解 `export` 與 `export default` 之間的區別。 -#### Fix the return statement {/*fix-the-return-statement*/} +#### 修復回傳內容 {/*fix-the-return-statement*/} -Something isn't right about this `return` statement. Can you fix it? +`return` 內容出了點問題,你能夠修復它嗎? -You may get an "Unexpected token" error while trying to fix this. In that case, check that the semicolon appears *after* the closing parenthesis. Leaving a semicolon inside `return ( )` will cause an error. +當你嘗試修復它的時候,你可能會收到「Unexpected token」的報錯。在這個情形下,請確認分號是否位於右括號 *之後*。在 `return ( )` 內留下分號將會導致錯誤發生。 @@ -318,7 +318,7 @@ img { height: 180px; } -You can fix this component by moving the return statement to one line like so: +你可以透過將回傳的內容移至同一行來修復這個問題,如下: @@ -334,7 +334,7 @@ img { height: 180px; } -Or by wrapping the returned JSX markup in parentheses that open right after `return`: +或者使用括號包裹回傳的 JSX markup,將左括號放在 `return` 的後面: @@ -357,9 +357,9 @@ img { height: 180px; } -#### Spot the mistake {/*spot-the-mistake*/} +#### 發現錯誤 {/*spot-the-mistake*/} -Something's wrong with how the `Profile` component is declared and used. Can you spot the mistake? (Try to remember how React distinguishes components from the regular HTML tags!) +`Profile` component 的宣告及使用發生了問題,你能指出其中的錯誤嗎?(試著回憶 React 是如何判別 component 與常規的 HTML 標籤!) @@ -393,9 +393,9 @@ img { margin: 0 10px 10px 0; height: 90px; } -React component names must start with a capital letter. +React component 的命名必須以大寫字母為首。 -Change `function profile()` to `function Profile()`, and then change every `` to ``: +將 `function profile()` 改為 `function Profile()`,然後將所有的 `` 改為 ``: @@ -429,9 +429,9 @@ img { margin: 0 10px 10px 0; } -#### Your own component {/*your-own-component*/} +#### 自定義 component {/*your-own-component*/} -Write a component from scratch. You can give it any valid name and return any markup. If you're out of ideas, you can write a `Congratulations` component that shows `

        Good job!

        `. Don't forget to export it! +從頭編寫一個 component。 你可以給定它任何有效名稱,然後回傳任何 markup。如果你沒有想法,你可以編寫一個顯示 `

        Good job!

        ` 的 `Congratulations` component。別忘了導出它!