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 legacy/createElement into Chinese #1210

Merged
merged 2 commits into from
Jun 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 51 additions & 51 deletions src/content/reference/react/createElement.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: createElement

<Intro>

`createElement` lets you create a React element. It serves as an alternative to writing [JSX.](/learn/writing-markup-with-jsx)
`createElement` 允许你创建一个 React 元素。它可以作为 [JSX](/learn/writing-markup-with-jsx) 的替代方案。

```js
const element = createElement(type, props, ...children)
Expand All @@ -16,11 +16,11 @@ const element = createElement(type, props, ...children)

---

## Reference {/*reference*/}
## 参考 {/*reference*/}

### `createElement(type, props, ...children)` {/*createelement*/}

Call `createElement` to create a React element with the given `type`, `props`, and `children`.
调用 `createElement` 来创建一个 React 元素,它有 `type``props` `children` 三个参数。

```js
import { createElement } from 'react';
Expand All @@ -29,93 +29,93 @@ function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello'
'你好'
);
}
```

[See more examples below.](#usage)
[查看更多例子](#usage)

#### Parameters {/*parameters*/}
#### 参数 {/*parameters*/}

* `type`: The `type` argument must be a valid React component type. For example, it could be a tag name string (such as `'div'` or `'span'`), or a React component (a function, a class, or a special component like [`Fragment`](/reference/react/Fragment)).
* `type``type` 参数必须是一个有效的 React 组件类型,例如一个字符串标签名(如 `'div'` `'span'`),或一个 React 组件(一个函数式组件、一个类式组件,或者是一个特殊的组件如 [`Fragment`](/reference/react/Fragment))。

* `props`: The `props` argument must either be an object or `null`. If you pass `null`, it will be treated the same as an empty object. React will create an element with props matching the `props` you have passed. Note that `ref` and `key` from your `props` object are special and will *not* be available as `element.props.ref` and `element.props.key` on the returned `element`. They will be available as `element.ref` and `element.key`.
* `props``props` 参数必须是一个对象或 `null`。如果你传入 `null`,它会被当作一个空对象。创建的 React 元素的 `props` 与这个参数相同。注意,`props` 对象中的 `ref` `key` 比较特殊,它们 **不会** 作为 `element.props.ref` `element.props.key` 出现在创建的元素 `element` 上,而是作为 `element.ref` `element.key` 出现。

* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/reference/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes.
* **可选** `...children`:零个或多个子节点。它们可以是任何 React 节点,包括 React 元素、字符串、数字、[portal](/reference/react-dom/createPortal)、空节点(`null``undefined``true` `false`),以及 React 节点数组。

#### Returns {/*returns*/}
#### 返回值 {/*returns*/}

`createElement` returns a React element object with a few properties:
`createElement` 返回一个 React 元素,它有这些属性:

* `type`: The `type` you have passed.
* `props`: The `props` you have passed except for `ref` and `key`. If the `type` is a component with legacy `type.defaultProps`, then any missing or undefined `props` will get the values from `type.defaultProps`.
* `ref`: The `ref` you have passed. If missing, `null`.
* `key`: The `key` you have passed, coerced to a string. If missing, `null`.
* `type`:你传入的 `type`
* `props`:你传入的 `props`,不包括 `ref` `key`。如果 `type` 是一个组件,且带有过时的 `type.defaultProps` 属性,那么 `props` 中任何缺失或未定义的字段都会采用 `type.defaultProps` 中的值。
* `ref`:你传入的 `ref`。如果缺失则为 `null`
* `key`:你传入的 `key`,会被强制转换为字符串。如果缺失则为 `null`

Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
通常你会在你组件的最后返回这个元素,或者把它作为另一个元素的子元素。虽然你可以读取元素的属性,但你最好把创建的元素作为黑盒,只用于渲染。

#### Caveats {/*caveats*/}
#### 注意事项 {/*caveats*/}

* You must **treat React elements and their props as [immutable](https://en.wikipedia.org/wiki/Immutable_object)** and never change their contents after creation. In development, React will [freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) the returned element and its `props` property shallowly to enforce this.
* 你必须 **把 React 元素和它们的 props 视为 [不可变的](https://en.wikipedia.org/wiki/Immutable_object)**,在创建后永远不要改变它们的内容。在开发环境中,React 会浅层 [冻结](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) 返回的元素及其 `props` 属性,以确保如此。

* When you use JSX, **you must start a tag with a capital letter to render your own custom component.** In other words, `<Something />` is equivalent to `createElement(Something)`, but `<something />` (lowercase) is equivalent to `createElement('something')` (note it's a string, so it will be treated as a built-in HTML tag).
* 当你使用 JSX 时,**你必须以大写字母开头来渲染你的自定义组件**。换句话说,`<Something />` 等价于 `createElement(Something)`,但 `<something />`(小写)等价于 `createElement('something')`(注意它是一个字符串,它会被当作内置的 HTML 标签)。

* You should only **pass children as multiple arguments to `createElement` if they are all statically known,** like `createElement('h1', {}, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `createElement('ul', {}, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
* 你应该仅 **在所有子元素都是静态可知的情况下,才将它们依次传递给 `createElement` 的可选参数**,比如 `createElement('h1', {}, child1, child2, child3)`。如果你的子元素不固定,则把它们放到数组中作为第三个参数传递,例如 `createElement('ul', {}, listItems)`,以此确保 React 可以在动态列表的场景下 [警告你缺少 `key`](/learn/rendering-lists#keeping-list-items-in-order-with-key)。静态列表的场景不需要这么做,因为它们不会重新排序。

---

## Usage {/*usage*/}
## 用法 {/*usage*/}

### Creating an element without JSX {/*creating-an-element-without-jsx*/}
## 不使用 JSX 创建元素 {/*creating-an-element-without-jsx*/}

If you don't like [JSX](/learn/writing-markup-with-jsx) or can't use it in your project, you can use `createElement` as an alternative.
如果你不喜欢 [JSX](/learn/writing-markup-with-jsx) 或者无法在你的项目中使用它,你可以使用 `createElement` 作为替代方案。

To create an element without JSX, call `createElement` with some <CodeStep step={1}>type</CodeStep>, <CodeStep step={2}>props</CodeStep>, and <CodeStep step={3}>children</CodeStep>:
要想不使用 JSX 创建一个元素,你可以调用 `createElement` 并传入 <CodeStep step={1}>type</CodeStep><CodeStep step={2}>props</CodeStep> <CodeStep step={3}>children</CodeStep>

```js [[1, 5, "'h1'"], [2, 6, "{ className: 'greeting' }"], [3, 7, "'Hello ',"], [3, 8, "createElement('i', null, name),"], [3, 9, "'. Welcome!'"]]
```js [[1, 5, "'h1'"], [2, 6, "{ className: 'greeting' }"], [3, 7, "'你好',"], [3, 8, "createElement('i', null, name),"], [3, 9, "'。欢迎!'"]]
import { createElement } from 'react';

function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello ',
'你好',
createElement('i', null, name),
'. Welcome!'
'。欢迎!'
);
}
```

The <CodeStep step={3}>children</CodeStep> are optional, and you can pass as many as you need (the example above has three children). This code will display a `<h1>` header with a greeting. For comparison, here is the same example rewritten with JSX:
<CodeStep step={3}>children</CodeStep> 是可选的,你可以传入任意数量的子元素(上面的例子中有三个)。这段代码会显示一个带有问候语的 `<h1>` 标题。为了对比,这是使用 JSX 的版本:

```js [[1, 3, "h1"], [2, 3, "className=\\"greeting\\""], [3, 4, "Hello <i>{name}</i>. Welcome!"], [1, 5, "h1"]]
```js [[1, 3, "h1"], [2, 3, "className=\\"greeting\\""], [3, 4, "你好<i>{name}</i>,欢迎!"], [1, 5, "h1"]]
function Greeting({ name }) {
return (
<h1 className="greeting">
Hello <i>{name}</i>. Welcome!
你好<i>{name}</i>,欢迎!
</h1>
);
}
```

To render your own React component, pass a function like `Greeting` as the <CodeStep step={1}>type</CodeStep> instead of a string like `'h1'`:
要想渲染你自己的 React 组件,则传入一个函数(比如 `Greeting`)作为 <CodeStep step={1}>type</CodeStep> ,而不是一个字符串(比如 `'h1'`):

```js [[1, 2, "Greeting"], [2, 2, "{ name: 'Taylor' }"]]
```js [[1, 2, "Greeting"], [2, 2, "{ name: '泰勒' }"]]
export default function App() {
return createElement(Greeting, { name: 'Taylor' });
return createElement(Greeting, { name: '泰勒' });
}
```

With JSX, it would look like this:
如果使用 JSX,它看起来像这样:

```js [[1, 2, "Greeting"], [2, 2, "name=\\"Taylor\\""]]
```js [[1, 2, "Greeting"], [2, 2, "name=\\"泰勒\\""]]
export default function App() {
return <Greeting name="Taylor" />;
return <Greeting name="泰勒" />;
}
```

Here is a complete example written with `createElement`:
这里是一个完整的使用 `createElement` 的示例:

<Sandpack>

Expand All @@ -126,16 +126,16 @@ function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello ',
'你好',
createElement('i', null, name),
'. Welcome!'
',欢迎!'
);
}

export default function App() {
return createElement(
Greeting,
{ name: 'Taylor' }
{ name: '泰勒' }
);
}
```
Expand All @@ -149,21 +149,21 @@ export default function App() {

</Sandpack>

And here is the same example written using JSX:
这里是相同的示例,但使用的是 JSX

<Sandpack>

```js
function Greeting({ name }) {
return (
<h1 className="greeting">
Hello <i>{name}</i>. Welcome!
你好<i>{name}</i>,欢迎!
</h1>
);
}

export default function App() {
return <Greeting name="Taylor" />;
return <Greeting name="泰勒" />;
}
```

Expand All @@ -176,30 +176,30 @@ export default function App() {

</Sandpack>

Both coding styles are fine, so you can use whichever one you prefer for your project. The main benefit of using JSX compared to `createElement` is that it's easy to see which closing tag corresponds to which opening tag.
两种编码风格都没问题,你可以在项目中使用任何一个你喜欢的风格。相比于 `createElement`,使用 JSX 的主要好处是很容易看出哪个闭合标签对应哪个开放标签。

<DeepDive>

#### What is a React element, exactly? {/*what-is-a-react-element-exactly*/}
#### React 元素究竟是什么? {/*what-is-a-react-element-exactly*/}

An element is a lightweight description of a piece of the user interface. For example, both `<Greeting name="Taylor" />` and `createElement(Greeting, { name: 'Taylor' })` produce an object like this:
元素是用来描述一部分用户界面的轻量级结构。比如,`<Greeting name="泰勒" />` `createElement(Greeting, { name: '泰勒' })` 都会生成一个这样的对象:

```js
// Slightly simplified
// 极度简化的样子
{
type: Greeting,
props: {
name: 'Taylor'
name: '泰勒'
},
key: null,
ref: null,
}
```

**Note that creating this object does not render the `Greeting` component or create any DOM elements.**
**注意,创建这个对象并不会渲染 `Greeting` 组件或者创建任何 DOM 元素**。

A React element is more like a description--an instruction for React to later render the `Greeting` component. By returning this object from your `App` component, you tell React what to do next.
React 元素更像是一个描述或指令,它告诉 React 之后该如何渲染 `Greeting` 组件。你从 `App` 组件中返回了这个对象,就是告诉了 React 接下来该做什么。

Creating elements is extremely cheap so you don't need to try to optimize or avoid it.
创建元素非常高效,因此你不需要试图优化或者避免它。

</DeepDive>