From f2fa8cd6a96b77bf848d8e65bccd5e69bc802543 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tarc=C3=ADsio=20Surdi?= Date: Sun, 30 Apr 2023 17:48:26 -0300 Subject: [PATCH 01/12] docs(pt-br): translated passing-props-to-a-component.md --- .../learn/passing-props-to-a-component.md | 149 +++++++++--------- 1 file changed, 74 insertions(+), 75 deletions(-) diff --git a/src/content/learn/passing-props-to-a-component.md b/src/content/learn/passing-props-to-a-component.md index da5fc5efc..52d75a922 100644 --- a/src/content/learn/passing-props-to-a-component.md +++ b/src/content/learn/passing-props-to-a-component.md @@ -1,26 +1,26 @@ --- -title: Passing Props to a Component +title: Passando Props a um Componente --- -React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions. +Componentes do React usam *props* para se comunicar um com ou outro. Todo componente pai pode passar alguma informação aos seus filhos por meio das *props*. Props podem te lembrar de atributos HTML, mas você pode passar qualquer valor JavaScript por meio delas, incluindo objetos, arrays, e funções. -* How to pass props to a component -* How to read props from a component -* How to specify default values for props -* How to pass some JSX to a component -* How props change over time +* Como passar props para um componente +* Como ler props de um componente +* Como especificar valores padrão para as props +* Como passar JSX a um componente +* Como as props mudam com o tempo -## Familiar props {/*familiar-props*/} +## Props familiares {/*familiar-props*/} -Props are the information that you pass to a JSX tag. For example, `className`, `src`, `alt`, `width`, and `height` are some of the props you can pass to an ``: +Props são as informações que você passa usando uma tag JSX. Por exemplo, `className`, `src`, `alt`, `width`, e `height` são algumas das props que você pode passar a uma ``: @@ -51,11 +51,11 @@ body { min-height: 120px; } -The props you can pass to an `` tag are predefined (ReactDOM conforms to [the HTML standard](https://www.w3.org/TR/html52/semantics-embedded-content.html#the-img-element)). But you can pass any props to *your own* components, such as ``, to customize them. Here's how! +As props que você pode passar a uma tag `` são predefinidas (A ReactDOM conforma-se ao [padrão HTML](https://www.w3.org/TR/html52/semantics-embedded-content.html#the-img-element)). Mas você pode passar quaisquer props aos *seus próprios* componentes, como um ``, para customizá-los. Veja como fazer isso! -## Passing props to a component {/*passing-props-to-a-component*/} +## Passando props para um componente {/*passing-props-to-a-component*/} -In this code, the `Profile` component isn't passing any props to its child component, `Avatar`: +Neste código, o componente `Profile` não está passando nenhuma prop aos seus componente filhos, `Avatar`: ```js export default function Profile() { @@ -65,11 +65,11 @@ export default function Profile() { } ``` -You can give `Avatar` some props in two steps. +Você pode atribuir algumas props ao `Avatar` em dois passos. -### Step 1: Pass props to the child component {/*step-1-pass-props-to-the-child-component*/} +### Passo 1: Passe props aos componentes filhos {/*step-1-pass-props-to-the-child-component*/} -First, pass some props to `Avatar`. For example, let's pass two props: `person` (an object), and `size` (a number): +Primeiro, passe algumas props ao `Avatar`. Por exemplo, vamos passar duas props: `person` (um objeto), e `size` (um número): ```js export default function Profile() { @@ -84,25 +84,25 @@ export default function Profile() { -If double curly braces after `person=` confuse you, recall [they're merely an object](/learn/javascript-in-jsx-with-curly-braces#using-double-curlies-css-and-other-objects-in-jsx) inside the JSX curlies. +Se as chaves duplas depois de `person=` lhe confundem, lembre-se [que elas são meramente um objeto](/learn/javascript-in-jsx-with-curly-braces#using-double-curlies-css-and-other-objects-in-jsx) na sintaxe JSX. -Now you can read these props inside the `Avatar` component. +Agora você pode ler essas props dentro do componente `Avatar`. -### Step 2: Read props inside the child component {/*step-2-read-props-inside-the-child-component*/} +### Passo 2: Leia props dentro de um componente filho {/*step-2-read-props-inside-the-child-component*/} -You can read these props by listing their names `person, size` separated by the commas inside `({` and `})` directly after `function Avatar`. This lets you use them inside the `Avatar` code, like you would with a variable. +Você pode ler estas propriedades listando seus nomes `person, size` separados por vírgulas diretamente dentro de `({` e `})` depois de `function Avatar`. Isso permite que você as use dentro do código de `Avatar`, assim como você faria com uma variável. ```js function Avatar({ person, size }) { - // person and size are available here + // person e size estão disponíveis aqui } ``` -Add some logic to `Avatar` that uses the `person` and `size` props for rendering, and you're done. +Adicione alguma lógica a `Avatar` que use as props `person` e `size` para a renderização, e pronto. -Now you can configure `Avatar` to render in many different ways with different props. Try tweaking the values! +Agora você pode configurar `Avatar` para que seja renderizado de várias maneiras diferentes usando props diferentes. Tente mudar os valores! @@ -168,9 +168,9 @@ body { min-height: 120px; } -Props let you think about parent and child components independently. For example, you can change the `person` or the `size` props inside `Profile` without having to think about how `Avatar` uses them. Similarly, you can change how the `Avatar` uses these props, without looking at the `Profile`. +Props permitem que você pense sobre os componentes pai e filho independentemente. Por exemplo, você pode mudar as props `person` e `size` dentro de `Profile` sem ter que pensar sobre como `Avatar` as usa. Similarmente, você é livre para mudar como `Avatar` usa essas props, sem checar o `Profile`. -You can think of props like "knobs" that you can adjust. They serve the same role as arguments serve for functions—in fact, props _are_ the only argument to your component! React component functions accept a single argument, a `props` object: +Você pode pensar nas props como "controles" os quais você pode ajustar. Elas desempenham o mesmo papel que os argumentos para funções--de fato, props _são_ o único argumento para o seu componente! Os componente funcionais do React aceitam apenas um argumento, um objeto `props`: ```js function Avatar(props) { @@ -180,11 +180,11 @@ function Avatar(props) { } ``` -Usually you don't need the whole `props` object itself, so you destructure it into individual props. +Normalmente você não precisa de todo o objeto `props` em si, então você pode desestruturá-lo em props individuais. -**Don't miss the pair of `{` and `}` curlies** inside of `(` and `)` when declaring props: +**Não esqueça o par `{` e `}`** dentro de `(` e `)` ao declarar props: ```js function Avatar({ person, size }) { @@ -192,7 +192,7 @@ function Avatar({ person, size }) { } ``` -This syntax is called ["destructuring"](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_a_function_parameter) and is equivalent to reading properties from a function parameter: +Essa sintaxe é chamada de ["desestruturação"](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_a_function_parameter) e é equivalente a ler propriedades de um parâmetro de função: ```js function Avatar(props) { @@ -204,9 +204,9 @@ function Avatar(props) { -## Specifying a default value for a prop {/*specifying-a-default-value-for-a-prop*/} +## Especificando um valor padrão a uma prop {/*specifying-a-default-value-for-a-prop*/} -If you want to give a prop a default value to fall back on when no value is specified, you can do it with the destructuring by putting `=` and the default value right after the parameter: +Se você quer dar a uma prop um valor padrão para usar quando nenhum for especificado, pode fazer isso com a desestruturação colocando `=` e um valor padrão logo depois do parâmetro: ```js function Avatar({ person, size = 100 }) { @@ -214,13 +214,13 @@ function Avatar({ person, size = 100 }) { } ``` -Now, if `` is rendered with no `size` prop, the `size` will be set to `100`. +Agora, se `` for renderizado sem uma prop `size`, `size` será igual a `100`. -The default value is only used if the `size` prop is missing or if you pass `size={undefined}`. But if you pass `size={null}` or `size={0}`, the default value will **not** be used. +O valor padrão só é utilizado se a prop `size` não for especificada ou se você passar `size={undefined}`. Mas caso você passe `size={null}` ou `size={0}`, o valor padrão **não** será usado. -## Forwarding props with the JSX spread syntax {/*forwarding-props-with-the-jsx-spread-syntax*/} +## Encaminhando props com a sintaxe de espalhamento JSX {/*forwarding-props-with-the-jsx-spread-syntax*/} -Sometimes, passing props gets very repetitive: +Às vezes, passar props se torna muito repetitivo: ```js function Profile({ person, size, isSepia, thickBorder }) { @@ -237,7 +237,7 @@ function Profile({ person, size, isSepia, thickBorder }) { } ``` -There's nothing wrong with repetitive code—it can be more legible. But at times you may value conciseness. Some components forward all of their props to their children, like how this `Profile` does with `Avatar`. Because they don't use any of their props directly, it can make sense to use a more concise "spread" syntax: +Não há nada de errado com o código repetitivo--ele pode ser mais legível. Mas por vezes você pode valorizar concisão. Alguns componentes encaminham todas as suas props aos seus filhos, como `Profile` faz com `Avatar`. Como ele não usa nenhuma de suas props diretamente, pode fazer sentido o uso da mais sucinta sintaxe de espalhamento: ```js function Profile(props) { @@ -249,13 +249,13 @@ function Profile(props) { } ``` -This forwards all of `Profile`'s props to the `Avatar` without listing each of their names. +Isso encaminha todas as props de `Profile` ao `Avatar` sem listar cada um de seus nomes. -**Use spread syntax with restraint.** If you're using it in every other component, something is wrong. Often, it indicates that you should split your components and pass children as JSX. More on that next! +**Use a sintaxe de espalhamento com cuidado.** Se você está a utilizando em quase todos os componentes, algo está errado. Geralmente, isso indica que você deveria separar seus componentes e passar filhos como JSX. Falaremos mais sobre isso agora! -## Passing JSX as children {/*passing-jsx-as-children*/} +## Passando JSX como filhos {/*passing-jsx-as-children*/} -It is common to nest built-in browser tags: +É comum aninhar tags embutidas no navegador: ```js
@@ -263,7 +263,7 @@ It is common to nest built-in browser tags:
``` -Sometimes you'll want to nest your own components the same way: +Às vezes será interessante aninhar seus componentes da mesma forma: ```js @@ -271,7 +271,7 @@ Sometimes you'll want to nest your own components the same way: ``` -When you nest content inside a JSX tag, the parent component will receive that content in a prop called `children`. For example, the `Card` component below will receive a `children` prop set to `` and render it in a wrapper div: +Quando você aninha conteúdo dentro de uma tag JSX, o componente pai irá recebê-lo dentro de uma prop denominada `children`. Exemplificando, o componente `Card` abaixo receberá a prop `children` definida como `` e o renderizará em uma div a qual o encapsula: @@ -347,17 +347,17 @@ export function getImageUrl(person, size = 's') { -Try replacing the `` inside `` with some text to see how the `Card` component can wrap any nested content. It doesn't need to "know" what's being rendered inside of it. You will see this flexible pattern in many places. +Tente substituir o `` dentro de `` com algum texto para ver como o componente `Card` pode encapsular conteúdo aninhado. Ele não precisa "saber" o que está sendo renderizado dentro dele. Você encontrará esse padrão flexível em muitos lugares. -You can think of a component with a `children` prop as having a "hole" that can be "filled in" by its parent components with arbitrary JSX. You will often use the `children` prop for visual wrappers: panels, grids, etc. +É possível pensar sobre um componente com a prop `children` como se ele tivesse um "buraco" o qual pode ser "preenchido" por seus componente pais com JSX arbitrária. Você frequentemente usará a prop `children` para encapsuladores visuais: painéis, grids, etc. -## How props change over time {/*how-props-change-over-time*/} +## Como props mudam com o passar do tempo {/*how-props-change-over-time*/} -The `Clock` component below receives two props from its parent component: `color` and `time`. (The parent component's code is omitted because it uses [state](/learn/state-a-components-memory), which we won't dive into just yet.) +O componente `Clock` abaixo recebe duas props de seu componente pai: `color` e `time`. (O código deste componente pai está omitido porque usa [state](/learn/state-a-components-memory), conceito o qual nós ainda não abordamos.) -Try changing the color in the select box below: +Tente mudar a cor na caixa de seleção abaixo: @@ -392,7 +392,7 @@ export default function App() { return (

- Pick a color:{' '} + Escolha uma cor:{' '}