From 9e72f3752a70c78916fbef433d52777cb8724287 Mon Sep 17 00:00:00 2001 From: Nivaldo Farias Date: Mon, 20 Jan 2025 17:11:36 -0300 Subject: [PATCH] Translate `createElement.md` to pt-br --- src/content/reference/react/createElement.md | 72 ++++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/src/content/reference/react/createElement.md b/src/content/reference/react/createElement.md index a5f684c66..328a335e8 100644 --- a/src/content/reference/react/createElement.md +++ b/src/content/reference/react/createElement.md @@ -4,7 +4,7 @@ title: createElement -`createElement` lets you create a React element. It serves as an alternative to writing [JSX.](/learn/writing-markup-with-jsx) +`createElement` permite que você crie um elemento React. Ele serve como uma alternativa para escrever [JSX](/learn/writing-markup-with-jsx). ```js const element = createElement(type, props, ...children) @@ -16,11 +16,11 @@ const element = createElement(type, props, ...children) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `createElement(type, props, ...children)` {/*createelement*/} -Call `createElement` to create a React element with the given `type`, `props`, and `children`. +Chame `createElement` para criar um elemento React com o `type`, `props` e `children` fornecidos. ```js import { createElement } from 'react'; @@ -34,44 +34,44 @@ function Greeting({ name }) { } ``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*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`: O argumento `type` deve ser um tipo de componente React válido. Por exemplo, pode ser uma string de nome de tag (como `'div'` ou `'span'`), ou um componente React (uma função, uma classe, ou um componente especial como [`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`: O argumento `props` deve ser um objeto ou `null`. Se você passar `null`, ele será tratado da mesma forma que um objeto vazio. O React criará um elemento com as props correspondentes às `props` que você passou. Note que `ref` e `key` do seu objeto `props` são especiais e *não* estarão disponíveis como `element.props.ref` e `element.props.key` no `element` retornado. Eles estarão disponíveis como `element.ref` e `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. +* **opcional** `...children`: Zero ou mais nós filhos. Eles podem ser quaisquer nós React, incluindo elementos React, strings, números, [portais](/reference/react-dom/createPortal), nós vazios (`null`, `undefined`, `true` e `false`), e arrays de nós React. -#### Returns {/*returns*/} +#### Retornos {/*returns*/} -`createElement` returns a React element object with a few properties: +`createElement` retorna um objeto de elemento React com algumas propriedades: -* `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`: O `type` que você passou. +* `props`: As `props` que você passou, exceto por `ref` e `key`. Se o `type` for um componente com `type.defaultProps` legados, então qualquer `props` faltante ou indefinida obterá os valores de `type.defaultProps`. +* `ref`: O `ref` que você passou. Se estiver ausente, `null`. +* `key`: A `key` que você passou, convertida em string. Se estiver ausente, `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. +Geralmente, você retornará o elemento do seu componente ou o tornará um filho de outro elemento. Embora você possa ler as propriedades do elemento, é melhor tratar cada elemento como opaco após sua criação e apenas renderizá-lo. -#### Caveats {/*caveats*/} +#### Ressalvas {/*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. +* Você deve **tratar os elementos React e suas props como [imutáveis](https://en.wikipedia.org/wiki/Immutable_object)** e nunca alterar seu conteúdo após a criação. Em desenvolvimento, o React irá [congelar](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) o elemento retornado e sua propriedade `props` superficialmente para impor isso. -* When you use JSX, **you must start a tag with a capital letter to render your own custom component.** In other words, `` is equivalent to `createElement(Something)`, but `` (lowercase) is equivalent to `createElement('something')` (note it's a string, so it will be treated as a built-in HTML tag). +* Quando você usar JSX, **você deve começar uma tag com letra maiúscula para renderizar seu próprio componente personalizado.** Em outras palavras, `` é equivalente a `createElement(Something)`, mas `` (minúscula) é equivalente a `createElement('something')` (note que é uma string, então será tratado como uma tag HTML incorporada). -* 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. +* Você deve **passar filhos como múltiplos argumentos para `createElement` apenas se todos forem estaticamente conhecidos**, como `createElement('h1', {}, child1, child2, child3)`. Se seus filhos forem dinâmicos, passe o array inteiro como o terceiro argumento: `createElement('ul', {}, listItems)`. Isso garante que o React [avise você sobre `keys` faltantes](/learn/rendering-lists#keeping-list-items-in-order-with-key) para quaisquer listas dinâmicas. Para listas estáticas isso não é necessário, pois elas nunca são reordenadas. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Creating an element without JSX {/*creating-an-element-without-jsx*/} +### Criando um elemento sem 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. +Se você não gosta de [JSX](/learn/writing-markup-with-jsx) ou não pode usá-lo em seu projeto, você pode usar `createElement` como alternativa. -To create an element without JSX, call `createElement` with some type, props, and children: +Para criar um elemento sem JSX, chame `createElement` com um type, props e children: ```js [[1, 5, "'h1'"], [2, 6, "{ className: 'greeting' }"], [3, 7, "'Hello ',"], [3, 8, "createElement('i', null, name),"], [3, 9, "'. Welcome!'"]] import { createElement } from 'react'; @@ -87,7 +87,7 @@ function Greeting({ name }) { } ``` -The children are optional, and you can pass as many as you need (the example above has three children). This code will display a `

` header with a greeting. For comparison, here is the same example rewritten with JSX: +Os children são opcionais, e você pode passar quantos precisar (o exemplo acima tem três filhos). Este código exibirá um cabeçalho `

` com uma saudação. Para comparação, aqui está o mesmo exemplo reescrito com JSX: ```js [[1, 3, "h1"], [2, 3, "className=\\"greeting\\""], [3, 4, "Hello {name}. Welcome!"], [1, 5, "h1"]] function Greeting({ name }) { @@ -99,7 +99,7 @@ function Greeting({ name }) { } ``` -To render your own React component, pass a function like `Greeting` as the type instead of a string like `'h1'`: +Para renderizar seu próprio componente React, passe uma função como `Greeting` como o type em vez de uma string como `'h1'`: ```js [[1, 2, "Greeting"], [2, 2, "{ name: 'Taylor' }"]] export default function App() { @@ -107,7 +107,7 @@ export default function App() { } ``` -With JSX, it would look like this: +Com JSX, ficaria assim: ```js [[1, 2, "Greeting"], [2, 2, "name=\\"Taylor\\""]] export default function App() { @@ -115,7 +115,7 @@ export default function App() { } ``` -Here is a complete example written with `createElement`: +Aqui está um exemplo completo escrito com `createElement`: @@ -149,7 +149,7 @@ export default function App() { -And here is the same example written using JSX: +E aqui está o mesmo exemplo escrito usando JSX: @@ -176,16 +176,16 @@ export default function App() { -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. +Ambos os estilos de codificação são bons, então você pode usar qualquer um que preferir para seu projeto. O principal benefício de usar JSX em comparação com `createElement` é que é fácil ver qual tag de fechamento corresponde à qual tag de abertura. -#### What is a React element, exactly? {/*what-is-a-react-element-exactly*/} +#### O que é exatamente um elemento React? {/*what-is-a-react-element-exactly*/} -An element is a lightweight description of a piece of the user interface. For example, both `` and `createElement(Greeting, { name: 'Taylor' })` produce an object like this: +Um elemento é uma descrição leve de uma parte da interface do usuário. Por exemplo, tanto `` quanto `createElement(Greeting, { name: 'Taylor' })` produzem um objeto como este: ```js -// Slightly simplified +// Levemente simplificado { type: Greeting, props: { @@ -196,10 +196,10 @@ An element is a lightweight description of a piece of the user interface. For ex } ``` -**Note that creating this object does not render the `Greeting` component or create any DOM elements.** +**Note que criar este objeto não renderiza o componente `Greeting` nem cria quaisquer elementos 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. +Um elemento React é mais como uma descrição—uma instrução para o React para renderizar mais tarde o componente `Greeting`. Ao retornar este objeto do seu componente `App`, você diz ao React o que fazer em seguida. -Creating elements is extremely cheap so you don't need to try to optimize or avoid it. +Criar elementos é extremamente barato, então você não precisa tentar otimizar ou evitá-lo. - + \ No newline at end of file