diff --git a/src/content/reference/react/Children.md b/src/content/reference/react/Children.md index 81a28c5b3..a63944979 100644 --- a/src/content/reference/react/Children.md +++ b/src/content/reference/react/Children.md @@ -4,13 +4,13 @@ title: Children -Using `Children` is uncommon and can lead to fragile code. [See common alternatives.](#alternatives) +Usar `Children` é incomum e pode levar a código frágil. [Veja alternativas comuns.](#alternatives) -`Children` lets you manipulate and transform the JSX you received as the [`children` prop.](/learn/passing-props-to-a-component#passing-jsx-as-children) +`Children` permite que você manipule e transforme o JSX que você recebeu como a [`children` prop.](/learn/passing-props-to-a-component#passing-jsx-as-children) ```js const mappedChildren = Children.map(children, child => @@ -27,11 +27,11 @@ const mappedChildren = Children.map(children, child => --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `Children.count(children)` {/*children-count*/} -Call `Children.count(children)` to count the number of children in the `children` data structure. +Chame `Children.count(children)` para contar o número de filhos na estrutura de dados `children`. ```js src/RowList.js active import { Children } from 'react'; @@ -39,32 +39,32 @@ import { Children } from 'react'; function RowList({ children }) { return ( <> -

Total rows: {Children.count(children)}

+

Total de linhas: {Children.count(children)}

... ); } ``` -[See more examples below.](#counting-children) +[Veja mais exemplos abaixo.](#counting-children) -#### Parameters {/*children-count-parameters*/} +#### Parâmetros {/*children-count-parameters*/} -* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component. +* `children`: O valor da [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) recebido pelo seu componente. -#### Returns {/*children-count-returns*/} +#### Retorna {/*children-count-returns*/} -The number of nodes inside these `children`. +O número de nós dentro desses `children`. -#### Caveats {/*children-count-caveats*/} +#### Ressalvas {/*children-count-caveats*/} -- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/reference/react/Fragment) don't get traversed. +- Nós vazios (`null`, `undefined` e Booleans), strings, números e [elementos React](/reference/react/createElement) contam como nós individuais. Arrays não contam como nós individuais, mas seus filhos contam. **A travessia não vai mais fundo do que elementos React:** eles não são renderizados, e seus filhos não são atravessados. [Fragmentos](/reference/react/Fragment) não são atravessados. --- ### `Children.forEach(children, fn, thisArg?)` {/*children-foreach*/} -Call `Children.forEach(children, fn, thisArg?)` to run some code for each child in the `children` data structure. +Chame `Children.forEach(children, fn, thisArg?)` para executar algum código para cada filho na estrutura de dados `children`. ```js src/RowList.js active import { Children } from 'react'; @@ -78,27 +78,27 @@ function SeparatorList({ children }) { // ... ``` -[See more examples below.](#running-some-code-for-each-child) +[Veja mais exemplos abaixo.](#running-some-code-for-each-child) -#### Parameters {/*children-foreach-parameters*/} +#### Parâmetros {/*children-foreach-parameters*/} -* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component. -* `fn`: The function you want to run for each child, similar to the [array `forEach` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call. -* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`. +* `children`: O valor da [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) recebido pelo seu componente. +* `fn`: A função que você deseja executar para cada filho, semelhante ao callback do [método `forEach` de array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). Ela será chamada com o filho como o primeiro argumento e seu índice como o segundo argumento. O índice começa em `0` e incrementa a cada chamada. +* **opcional** `thisArg`: O [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) com o qual a função `fn` deve ser chamada. Se omitido, é `undefined`. -#### Returns {/*children-foreach-returns*/} +#### Retorna {/*children-foreach-returns*/} -`Children.forEach` returns `undefined`. +`Children.forEach` retorna `undefined`. -#### Caveats {/*children-foreach-caveats*/} +#### Ressalvas {/*children-foreach-caveats*/} -- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/reference/react/Fragment) don't get traversed. +- Nós vazios (`null`, `undefined` e Booleans), strings, números e [elementos React](/reference/react/createElement) contam como nós individuais. Arrays não contam como nós individuais, mas seus filhos contam. **A travessia não vai mais fundo do que elementos React:** eles não são renderizados, e seus filhos não são atravessados. [Fragmentos](/reference/react/Fragment) não são atravessados. --- ### `Children.map(children, fn, thisArg?)` {/*children-map*/} -Call `Children.map(children, fn, thisArg?)` to map or transform each child in the `children` data structure. +Chame `Children.map(children, fn, thisArg?)` para mapear ou transformar cada filho na estrutura de dados `children`. ```js src/RowList.js active import { Children } from 'react'; @@ -116,32 +116,32 @@ function RowList({ children }) { } ``` -[See more examples below.](#transforming-children) +[Veja mais exemplos abaixo.](#transforming-children) -#### Parameters {/*children-map-parameters*/} +#### Parâmetros {/*children-map-parameters*/} -* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component. -* `fn`: The mapping function, similar to the [array `map` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call. You need to return a React node from this function. This may be an empty node (`null`, `undefined`, or a Boolean), a string, a number, a React element, or an array of other React nodes. -* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`. +* `children`: O valor da [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) recebido pelo seu componente. +* `fn`: A função de mapeamento, semelhante ao callback do [método `map` de array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Ela será chamada com o filho como o primeiro argumento e seu índice como o segundo argumento. O índice começa em `0` e incrementa a cada chamada. Você precisa retornar um nó React desta função. Isso pode ser um nó vazio (`null`, `undefined` ou um Boolean), uma string, um número, um elemento React ou um array de outros nós React. +* **opcional** `thisArg`: O [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) com o qual a função `fn` deve ser chamada. Se omitido, é `undefined`. -#### Returns {/*children-map-returns*/} +#### Retorna {/*children-map-returns*/} -If `children` is `null` or `undefined`, returns the same value. +Se `children` é `null` ou `undefined`, retorna o mesmo valor. -Otherwise, returns a flat array consisting of the nodes you've returned from the `fn` function. The returned array will contain all nodes you returned except for `null` and `undefined`. +Caso contrário, retorna um array plano consistindo dos nós que você retornou da função `fn`. O array retornado conterá todos os nós que você retornou, exceto `null` e `undefined`. -#### Caveats {/*children-map-caveats*/} +#### Ressalvas {/*children-map-caveats*/} -- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/reference/react/Fragment) don't get traversed. +- Nós vazios (`null`, `undefined` e Booleans), strings, números e [elementos React](/reference/react/createElement) contam como nós individuais. Arrays não contam como nós individuais, mas seus filhos contam. **A travessia não vai mais fundo do que elementos React:** eles não são renderizados, e seus filhos não são atravessados. [Fragmentos](/reference/react/Fragment) não são atravessados. -- If you return an element or an array of elements with keys from `fn`, **the returned elements' keys will be automatically combined with the key of the corresponding original item from `children`.** When you return multiple elements from `fn` in an array, their keys only need to be unique locally amongst each other. +- Se você retornar um elemento ou um array de elementos com chaves de `fn`, **as chaves dos elementos retornados serão automaticamente combinadas com a chave do item original correspondente de `children`.** Quando você retorna múltiplos elementos de `fn` em um array, suas chaves só precisam ser únicas localmente entre si. --- ### `Children.only(children)` {/*children-only*/} -Call `Children.only(children)` to assert that `children` represent a single React element. +Chame `Children.only(children)` para afirmar que `children` representa um único elemento React. ```js function Box({ children }) { @@ -149,25 +149,25 @@ function Box({ children }) { // ... ``` -#### Parameters {/*children-only-parameters*/} +#### Parâmetros {/*children-only-parameters*/} -* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component. +* `children`: O valor da [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) recebido pelo seu componente. -#### Returns {/*children-only-returns*/} +#### Retorna {/*children-only-returns*/} -If `children` [is a valid element,](/reference/react/isValidElement) returns that element. +Se `children` [é um elemento válido,](/reference/react/isValidElement) retorna esse elemento. -Otherwise, throws an error. +Caso contrário, lança um erro. -#### Caveats {/*children-only-caveats*/} +#### Ressalvas {/*children-only-caveats*/} -- This method always **throws if you pass an array (such as the return value of `Children.map`) as `children`.** In other words, it enforces that `children` is a single React element, not that it's an array with a single element. +- Este método sempre **lança uma exceção se você passar um array (como o valor de retorno de `Children.map`) como `children`.** Em outras palavras, ele impõe que `children` seja um único elemento React, não que seja um array com um único elemento. --- ### `Children.toArray(children)` {/*children-toarray*/} -Call `Children.toArray(children)` to create an array out of the `children` data structure. +Chame `Children.toArray(children)` para criar um array a partir da estrutura de dados `children`. ```js src/ReversedList.js active import { Children } from 'react'; @@ -178,25 +178,25 @@ export default function ReversedList({ children }) { // ... ``` -#### Parameters {/*children-toarray-parameters*/} +#### Parâmetros {/*children-toarray-parameters*/} -* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component. +* `children`: O valor da [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) recebido pelo seu componente. -#### Returns {/*children-toarray-returns*/} +#### Retorna {/*children-toarray-returns*/} -Returns a flat array of elements in `children`. +Retorna um array plano de elementos em `children`. -#### Caveats {/*children-toarray-caveats*/} +#### Ressalvas {/*children-toarray-caveats*/} -- Empty nodes (`null`, `undefined`, and Booleans) will be omitted in the returned array. **The returned elements' keys will be calculated from the original elements' keys and their level of nesting and position.** This ensures that flattening the array does not introduce changes in behavior. +- Nós vazios (`null`, `undefined` e Booleans) serão omitidos no array retornado. **As chaves dos elementos retornados serão calculadas a partir das chaves dos elementos originais e seu nível de aninhamento e posição.** Isso garante que achatar o array não introduza mudanças no comportamento. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Transforming children {/*transforming-children*/} +### Transformando filhos {/*transforming-children*/} -To transform the children JSX that your component [receives as the `children` prop,](/learn/passing-props-to-a-component#passing-jsx-as-children) call `Children.map`: +Para transformar o JSX de filhos que seu componente [recebe como a `children` prop,](/learn/passing-props-to-a-component#passing-jsx-as-children) chame `Children.map`: ```js {6,10} import { Children } from 'react'; @@ -214,33 +214,33 @@ function RowList({ children }) { } ``` -In the example above, the `RowList` wraps every child it receives into a `
` container. For example, let's say the parent component passes three `

` tags as the `children` prop to `RowList`: +No exemplo acima, o `RowList` envolve cada filho que recebe em um contêiner `

`. Por exemplo, digamos que o componente pai passe três tags `

` como a `children` prop para `RowList`: ```js -

This is the first item.

-

This is the second item.

-

This is the third item.

+

Este é o primeiro item.

+

Este é o segundo item.

+

Este é o terceiro item.

``` -Then, with the `RowList` implementation above, the final rendered result will look like this: +Então, com a implementação do `RowList` acima, o resultado renderizado final ficará assim: ```js
-

This is the first item.

+

Este é o primeiro item.

-

This is the second item.

+

Este é o segundo item.

-

This is the third item.

+

Este é o terceiro item.

``` -`Children.map` is similar to [to transforming arrays with `map()`.](/learn/rendering-lists) The difference is that the `children` data structure is considered *opaque.* This means that even if it's sometimes an array, you should not assume it's an array or any other particular data type. This is why you should use `Children.map` if you need to transform it. +`Children.map` é semelhante a [transformar arrays com `map()`.](/learn/rendering-lists) A diferença é que a estrutura de dados `children` é considerada *opaca.* Isso significa que mesmo que às vezes seja um array, você não deve assumir que é um array ou qualquer outro tipo de dado específico. Por isso, você deve usar `Children.map` se precisar transformá-lo. @@ -250,9 +250,9 @@ import RowList from './RowList.js'; export default function App() { return ( -

This is the first item.

-

This is the second item.

-

This is the third item.

+

Este é o primeiro item.

+

Este é o segundo item.

+

Este é o terceiro item.

); } @@ -293,24 +293,24 @@ export default function RowList({ children }) { -#### Why is the children prop not always an array? {/*why-is-the-children-prop-not-always-an-array*/} +#### Por que a prop children nem sempre é um array? {/*why-is-the-children-prop-not-always-an-array*/} -In React, the `children` prop is considered an *opaque* data structure. This means that you shouldn't rely on how it is structured. To transform, filter, or count children, you should use the `Children` methods. +No React, a prop `children` é considerada uma estrutura de dados *opaca*. Isso significa que você não deve depender de como ela está estruturada. Para transformar, filtrar ou contar filhos, você deve usar os métodos `Children`. -In practice, the `children` data structure is often represented as an array internally. However, if there is only a single child, then React won't create an extra array since this would lead to unnecessary memory overhead. As long as you use the `Children` methods instead of directly introspecting the `children` prop, your code will not break even if React changes how the data structure is actually implemented. +Na prática, a estrutura de dados `children` é frequentemente representada como um array internamente. No entanto, se houver apenas um único filho, o React não criará um array extra, pois isso levaria a uma sobrecarga desnecessária de memória. Enquanto você usar os métodos `Children` em vez de introspectar diretamente a prop `children`, seu código não quebrará mesmo que o React mude como a estrutura de dados é realmente implementada. -Even when `children` is an array, `Children.map` has useful special behavior. For example, `Children.map` combines the [keys](/learn/rendering-lists#keeping-list-items-in-order-with-key) on the returned elements with the keys on the `children` you've passed to it. This ensures the original JSX children don't "lose" keys even if they get wrapped like in the example above. +Mesmo quando `children` é um array, `Children.map` tem um comportamento especial útil. Por exemplo, `Children.map` combina as [chaves](/learn/rendering-lists#keeping-list-items-in-order-with-key) nos elementos retornados com as chaves nos `children` que você passou para ele. Isso garante que os filhos JSX originais não "percam" chaves, mesmo que sejam envoltos como no exemplo acima. -The `children` data structure **does not include rendered output** of the components you pass as JSX. In the example below, the `children` received by the `RowList` only contains two items rather than three: +A estrutura de dados `children` **não inclui a saída renderizada** dos componentes que você passa como JSX. No exemplo abaixo, os `children` recebidos pelo `RowList` contêm apenas dois itens, em vez de três: -1. `

This is the first item.

` +1. `

Este é o primeiro item.

` 2. `` -This is why only two row wrappers are generated in this example: +É por isso que apenas duas envoltórias de linha são geradas neste exemplo: @@ -320,7 +320,7 @@ import RowList from './RowList.js'; export default function App() { return ( -

This is the first item.

+

Este é o primeiro item.

); @@ -329,8 +329,8 @@ export default function App() { function MoreRows() { return ( <> -

This is the second item.

-

This is the third item.

+

Este é o segundo item.

+

Este é o terceiro item.

); } @@ -369,15 +369,15 @@ export default function RowList({ children }) {
-**There is no way to get the rendered output of an inner component** like `` when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives) +**Não há como obter a saída renderizada de um componente interno** como `` ao manipular `children`. É por isso que [geralmente é melhor usar uma das soluções alternativas.](#alternatives)
--- -### Running some code for each child {/*running-some-code-for-each-child*/} +### Executando algum código para cada filho {/*running-some-code-for-each-child*/} -Call `Children.forEach` to iterate over each child in the `children` data structure. It does not return any value and is similar to the [array `forEach` method.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) You can use it to run custom logic like constructing your own array. +Chame `Children.forEach` para iterar sobre cada filho na estrutura de dados `children`. Ele não retorna nenhum valor e é semelhante ao [método `forEach` de array.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) Você pode usá-lo para executar lógica personalizada, como construir seu próprio array. @@ -387,9 +387,9 @@ import SeparatorList from './SeparatorList.js'; export default function App() { return ( -

This is the first item.

-

This is the second item.

-

This is the third item.

+

Este é o primeiro item.

+

Este é o segundo item.

+

Este é o terceiro item.

); } @@ -404,7 +404,7 @@ export default function SeparatorList({ children }) { result.push(child); result.push(
); }); - result.pop(); // Remove the last separator + result.pop(); // Remove o último separador return result; } ``` @@ -413,15 +413,15 @@ export default function SeparatorList({ children }) { -As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives) +Como mencionado anteriormente, não há como obter a saída renderizada de um componente interno ao manipular `children`. É por isso que [geralmente é melhor usar uma das soluções alternativas.](#alternatives) --- -### Counting children {/*counting-children*/} +### Contando filhos {/*counting-children*/} -Call `Children.count(children)` to calculate the number of children. +Chame `Children.count(children)` para calcular o número de filhos. @@ -431,9 +431,9 @@ import RowList from './RowList.js'; export default function App() { return ( -

This is the first item.

-

This is the second item.

-

This is the third item.

+

Este é o primeiro item.

+

Este é o segundo item.

+

Este é o terceiro item.

); } @@ -446,7 +446,7 @@ export default function RowList({ children }) { return (

- Total rows: {Children.count(children)} + Total de linhas: {Children.count(children)}

{Children.map(children, child =>
@@ -484,15 +484,15 @@ export default function RowList({ children }) { -As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives) +Como mencionado anteriormente, não há como obter a saída renderizada de um componente interno ao manipular `children`. É por isso que [geralmente é melhor usar uma das soluções alternativas.](#alternatives) --- -### Converting children to an array {/*converting-children-to-an-array*/} +### Convertendo filhos em um array {/*converting-children-to-an-array*/} -Call `Children.toArray(children)` to turn the `children` data structure into a regular JavaScript array. This lets you manipulate the array with built-in array methods like [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), or [`reverse`.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) +Chame `Children.toArray(children)` para transformar a estrutura de dados `children` em um array JavaScript regular. Isso permite que você manipule o array com métodos de array incorporados como [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) ou [`reverse`.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) @@ -502,9 +502,9 @@ import ReversedList from './ReversedList.js'; export default function App() { return ( -

This is the first item.

-

This is the second item.

-

This is the third item.

+

Este é o primeiro item.

+

Este é o segundo item.

+

Este é o terceiro item.

); } @@ -524,31 +524,31 @@ export default function ReversedList({ children }) { -As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives) +Como mencionado anteriormente, não há como obter a saída renderizada de um componente interno ao manipular `children`. É por isso que [geralmente é melhor usar uma das soluções alternativas.](#alternatives) --- -## Alternatives {/*alternatives*/} +## Alternativas {/*alternatives*/} -This section describes alternatives to the `Children` API (with capital `C`) that's imported like this: +Esta seção descreve alternativas à API `Children` (com `C` maiúsculo) que é importada assim: ```js import { Children } from 'react'; ``` -Don't confuse it with [using the `children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) (lowercase `c`), which is good and encouraged. +Não confunda isso com [usar a prop `children` ](/learn/passing-props-to-a-component#passing-jsx-as-children) (com `c` minúsculo), que é boa e incentivada. -### Exposing multiple components {/*exposing-multiple-components*/} +### Expondo múltiplos componentes {/*exposing-multiple-components*/} -Manipulating children with the `Children` methods often leads to fragile code. When you pass children to a component in JSX, you don't usually expect the component to manipulate or transform the individual children. +Manipular filhos com os métodos `Children` muitas vezes leva a código frágil. Quando você passa filhos para um componente em JSX, geralmente não espera que o componente manipule ou transforme os filhos individuais. -When you can, try to avoid using the `Children` methods. For example, if you want every child of `RowList` to be wrapped in `
`, export a `Row` component, and manually wrap every row into it like this: +Quando puder, tente evitar usar os métodos `Children`. Por exemplo, se você quiser que cada filho de `RowList` seja envolvido em `
`, exporte um componente `Row` e envolva manualmente cada linha assim: @@ -559,13 +559,13 @@ export default function App() { return ( -

This is the first item.

+

Este é o primeiro item.

-

This is the second item.

+

Este é o segundo item.

-

This is the third item.

+

Este é o terceiro item.

); @@ -607,7 +607,7 @@ export function Row({ children }) {
-Unlike using `Children.map`, this approach does not wrap every child automatically. **However, this approach has a significant benefit compared to the [earlier example with `Children.map`](#transforming-children) because it works even if you keep extracting more components.** For example, it still works if you extract your own `MoreRows` component: +Diferente de usar `Children.map`, essa abordagem não envolve automaticamente cada filho. **No entanto, essa abordagem tem um benefício significativo comparado ao [exemplo anterior com `Children.map`](#transforming-children) porque funciona mesmo se você continuar extraindo mais componentes.** Por exemplo, ainda funciona se você extrair seu próprio componente `MoreRows`: @@ -618,7 +618,7 @@ export default function App() { return ( -

This is the first item.

+

Este é o primeiro item.

@@ -629,10 +629,10 @@ function MoreRows() { return ( <> -

This is the second item.

+

Este é o segundo item.

-

This is the third item.

+

Este é o terceiro item.

); @@ -674,13 +674,13 @@ export function Row({ children }) {
-This wouldn't work with `Children.map` because it would "see" `` as a single child (and a single row). +Isso não funcionaria com `Children.map` porque "veria" `` como um filho único (e uma única linha). --- -### Accepting an array of objects as a prop {/*accepting-an-array-of-objects-as-a-prop*/} +### Aceitando um array de objetos como uma prop {/*accepting-an-array-of-objects-as-a-prop*/} -You can also explicitly pass an array as a prop. For example, this `RowList` accepts a `rows` array as a prop: +Você também pode passar explicitamente um array como uma prop. Por exemplo, este `RowList` aceita um array `rows` como uma prop: @@ -690,9 +690,9 @@ import { RowList, Row } from './RowList.js'; export default function App() { return ( This is the first item.

}, - { id: 'second', content:

This is the second item.

}, - { id: 'third', content:

This is the third item.

} + { id: 'first', content:

Este é o primeiro item.

}, + { id: 'second', content:

Este é o segundo item.

}, + { id: 'third', content:

Este é o terceiro item.

} ]} /> ); } @@ -729,9 +729,9 @@ export function RowList({ rows }) {
-Since `rows` is a regular JavaScript array, the `RowList` component can use built-in array methods like [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) on it. +Como `rows` é um array JavaScript regular, o componente `RowList` pode usar métodos de array incorporados como [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) nele. -This pattern is especially useful when you want to be able to pass more information as structured data together with children. In the below example, the `TabSwitcher` component receives an array of objects as the `tabs` prop: +Esse padrão é especialmente útil quando você deseja poder passar mais informações como dados estruturados junto com os filhos. No exemplo abaixo, o componente `TabSwitcher` recebe um array de objetos como a prop `tabs`: @@ -743,18 +743,18 @@ export default function App() { This is the first item.

+ header: 'Primeiro', + content:

Este é o primeiro item.

}, { id: 'second', - header: 'Second', - content:

This is the second item.

+ header: 'Segundo', + content:

Este é o segundo item.

}, { id: 'third', - header: 'Third', - content:

This is the third item.

+ header: 'Terceiro', + content:

Este é o terceiro item.

} ]} /> ); @@ -789,13 +789,13 @@ export default function TabSwitcher({ tabs }) {
-Unlike passing the children as JSX, this approach lets you associate some extra data like `header` with each item. Because you are working with the `tabs` directly, and it is an array, you do not need the `Children` methods. +Diferente de passar os filhos como JSX, essa abordagem permite que você associe alguns dados extras como `header` com cada item. Como você está trabalhando diretamente com os `tabs`, e este é um array, você não precisa dos métodos `Children`. --- -### Calling a render prop to customize rendering {/*calling-a-render-prop-to-customize-rendering*/} +### Chamando uma função de renderização para personalizar a renderização {/*calling-a-render-prop-to-customize-rendering*/} -Instead of producing JSX for every single item, you can also pass a function that returns JSX, and call that function when necessary. In this example, the `App` component passes a `renderContent` function to the `TabSwitcher` component. The `TabSwitcher` component calls `renderContent` only for the selected tab: +Em vez de produzir JSX para cada item único, você também pode passar uma função que retorna JSX e chamar essa função quando necessário. Neste exemplo, o componente `App` passa uma função `renderContent` para o componente `TabSwitcher`. O componente `TabSwitcher` chama `renderContent` apenas para a aba selecionada: @@ -810,7 +810,7 @@ export default function App() { return tabId[0].toUpperCase() + tabId.slice(1); }} renderContent={tabId => { - return

This is the {tabId} item.

; + return

Este é o item {tabId}.

; }} /> ); @@ -844,9 +844,9 @@ export default function TabSwitcher({ tabIds, getHeader, renderContent }) {
-A prop like `renderContent` is called a *render prop* because it is a prop that specifies how to render a piece of the user interface. However, there is nothing special about it: it is a regular prop which happens to be a function. +Uma prop como `renderContent` é chamada de *render prop* porque é uma prop que especifica como renderizar uma parte da interface do usuário. No entanto, não há nada de especial sobre isso: é uma prop regular que acontece de ser uma função. -Render props are functions, so you can pass information to them. For example, this `RowList` component passes the `id` and the `index` of each row to the `renderRow` render prop, which uses `index` to highlight even rows: +Render props são funções, então você pode passar informações para elas. Por exemplo, este componente `RowList` passa o `id` e o `index` de cada linha para o render prop `renderRow`, que usa `index` para destacar linhas pares: @@ -860,7 +860,7 @@ export default function App() { renderRow={(id, index) => { return ( -

This is the {id} item.

+

Este é o item {id}.

); }} @@ -876,7 +876,7 @@ export function RowList({ rowIds, renderRow }) { return (

- Total rows: {rowIds.length} + Total de linhas: {rowIds.length}

{rowIds.map((rowId, index) => @@ -927,23 +927,23 @@ export function Row({ children, isHighlighted }) { -This is another example of how parent and child components can cooperate without manipulating the children. +Este é outro exemplo de como componentes pai e filho podem cooperar sem manipular os filhos. --- -## Troubleshooting {/*troubleshooting*/} +## Solução de Problemas {/*troubleshooting*/} -### I pass a custom component, but the `Children` methods don't show its render result {/*i-pass-a-custom-component-but-the-children-methods-dont-show-its-render-result*/} +### Eu passo um componente personalizado, mas os métodos `Children` não mostram seu resultado de renderização {/*i-pass-a-custom-component-but-the-children-methods-dont-show-its-render-result*/} -Suppose you pass two children to `RowList` like this: +Suponha que você passe dois filhos para `RowList` assim: ```js -

First item

+

Primeiro item

``` -If you do `Children.count(children)` inside `RowList`, you will get `2`. Even if `MoreRows` renders 10 different items, or if it returns `null`, `Children.count(children)` will still be `2`. From the `RowList`'s perspective, it only "sees" the JSX it has received. It does not "see" the internals of the `MoreRows` component. +Se você fizer `Children.count(children)` dentro de `RowList`, obterá `2`. Mesmo que `MoreRows` renderize 10 itens diferentes, ou se retornar `null`, `Children.count(children)` ainda será `2`. Do ponto de vista do `RowList`, ele só "vê" o JSX que recebeu. Ele não "vê" os internos do componente `MoreRows`. -The limitation makes it hard to extract a component. This is why [alternatives](#alternatives) are preferred to using `Children`. +A limitação torna difícil extrair um componente. É por isso que [soluções alternativas](#alternatives) são preferidas ao usar `Children`. \ No newline at end of file