Skip to content

Commit 0a54ea4

Browse files
authored
Translate adding-interactivity.md to Portuguese (#1089)
1 parent 9769b26 commit 0a54ea4

File tree

1 file changed

+53
-51
lines changed

1 file changed

+53
-51
lines changed

src/content/learn/adding-interactivity.md

Lines changed: 53 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
11
---
2-
title: Adding Interactivity
2+
title: Adicionando Interatividade
33
---
44

55
<Intro>
66

7-
Some things on the screen update in response to user input. For example, clicking an image gallery switches the active image. In React, data that changes over time is called *state.* You can add state to any component, and update it as needed. In this chapter, you'll learn how to write components that handle interactions, update their state, and display different output over time.
7+
Alguns elementos na tela se atualizam em resposta às entradas do usuário. Por exemplo, ao clicar em uma galeria de imagens, a imagem ativa é trocada. Em React, os dados que mudam ao longo do tempo são chamados de *state.* Você pode adicionar states a qualquer componente, e atualizá-los quando necessário. Neste capítulo, você aprenderá como escrever componentes que gerenciam interações, atualizam seus states, e apresentam diferentes saídas ao longo do tempo.
88

99
</Intro>
1010

1111
<YouWillLearn isChapter={true}>
1212

13-
* [How to handle user-initiated events](/learn/responding-to-events)
14-
* [How to make components "remember" information with state](/learn/state-a-components-memory)
15-
* [How React updates the UI in two phases](/learn/render-and-commit)
16-
* [Why state doesn't update right after you change it](/learn/state-as-a-snapshot)
17-
* [How to queue multiple state updates](/learn/queueing-a-series-of-state-updates)
18-
* [How to update an object in state](/learn/updating-objects-in-state)
19-
* [How to update an array in state](/learn/updating-arrays-in-state)
13+
* [Como manipular eventos acionados pelo usuário](/learn/responding-to-events)
14+
* [Como fazer os componentes "memorizarem" informações com o state](/learn/state-a-components-memory)
15+
* [Como o React atualiza a UI em duas fases](/learn/render-and-commit)
16+
* [Porque o state não atualiza logo após ser alterado](/learn/state-as-a-snapshot)
17+
* [Como enfileirar múltiplas atualizações no state](/learn/queueing-a-series-of-state-updates)
18+
* [Como atualizar um objeto no state](/learn/updating-objects-in-state)
19+
* [Como atualizar um array no state](/learn/updating-arrays-in-state)
2020

2121
</YouWillLearn>
2222

23-
## Responding to events {/*responding-to-events*/}
23+
## Respondendo a eventos {/*responding-to-events*/}
2424

25-
React lets you add *event handlers* to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
25+
Componentes embutidos, a exemplo do `<button>` apenas são compatíveis com eventos de navegador, como `onClick`.
2626

27-
Built-in components like `<button>` only support built-in browser events like `onClick`. However, you can also create your own components, and give their event handler props any application-specific names that you like.
27+
No entanto, você também pode criar seus próprios componentes e atribuir aos props de seus manipuladores de eventos quaisquer nomes específicos da aplicação que considerar adequados.
2828

2929
<Sandpack>
3030

@@ -68,22 +68,22 @@ button { margin-right: 10px; }
6868

6969
<LearnMore path="/learn/responding-to-events">
7070

71-
Read **[Responding to Events](/learn/responding-to-events)** to learn how to add event handlers.
71+
Leia **[Respondendo a Eventos](/learn/responding-to-events)** para aprender como adicionar manipuladores de eventos.
7272

7373
</LearnMore>
7474

75-
## State: a component's memory {/*state-a-components-memory*/}
75+
## State: A memória de um componente {/*state-a-components-memory*/}
7676

77-
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state.*
77+
Componentes necessitam de alterar frequentemente o que está na tela como resultado de uma interação. O campo de entrada será atualizado ao digitar em um formulário, a imagem exibida será trocada ao clicar em "próxima" em um carrossel de imagens, um produto é colocado no carrinho de compras ao clicar em "comprar". Componentes precisam "memorizar" informações: o valor de entrada ou a imagem atual, assim como o carrinho de compras, por exemplo. Em React, este tipo de memória específica de componente é chamada de *state.*
7878

79-
You can add state to a component with a [`useState`](/apis/usestate) Hook. Hooks are special functions that let your components use React features (state is one of those features). The `useState` Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
79+
É possível adicionar states a componentes com um Hook [`useState`](/apis/usestate). Hooks são funções especiais que possibilitam que seus componentes utilizem recursos do React (como o state, por exemplo). O Hook `useState` possibilita a declaração de uma variável de estado. Este recurso recebe o state inicial e retorna um par de valores: o state atual e uma função setter, que possibilita atualizá-lo.
8080

8181
```js
8282
const [index, setIndex] = useState(0);
8383
const [showMore, setShowMore] = useState(false);
8484
```
8585

86-
Here is how an image gallery uses and updates state on click:
86+
Veja como uma galeria de imagens utiliza e atualiza um state com cliques:
8787

8888
<Sandpack>
8989

@@ -229,43 +229,45 @@ button {
229229

230230
<LearnMore path="/learn/state-a-components-memory">
231231

232-
Read **[State: A Component's Memory](/learn/state-a-components-memory)** to learn how to remember a value and update it on interaction.
232+
Leia **[State: A Memória de um Componente](/learn/state-a-components-memory)** para aprender como memorizar um valor e atualizá-lo com interatividade.
233233

234234
</LearnMore>
235235

236-
## Render and commit {/*render-and-commit*/}
236+
## Renderizar e confirmar {/*render-and-commit*/}
237237

238-
Before your components are displayed on the screen, they must be rendered by React. Understanding the steps in this process will help you think about how your code executes and explain its behavior.
238+
Antes que seus componentes sejam exibidos na tela, eles devem ser renderizados pelo React.
239239

240-
Imagine that your components are cooks in the kitchen, assembling tasty dishes from ingredients. In this scenario, React is the waiter who puts in requests from customers and brings them their orders. This process of requesting and serving UI has three steps:
240+
O entendimento dos passos neste processo irá ajudá-lo a pensar sobre como o seu código executa e explicará seu comportamento.
241241

242-
1. **Triggering** a render (delivering the diner's order to the kitchen)
243-
2. **Rendering** the component (preparing the order in the kitchen)
244-
3. **Committing** to the DOM (placing the order on the table)
242+
Imagine que seus componentes são chefs na cozinha, montando pratos saborosos a partir de ingredientes. Neste cenário, o React é o garçom que recebe as solicitações dos clientes e lhes traz o que foi pedido. Este processo de solicitar e servir a UI consiste em tres etapas:
243+
244+
1. **Acionamento** da renderização (entrega do pedido do cliente à cozinha)
245+
2. **Renderização** do componente (preparo da solicitação na cozinha)
246+
3. **Confirmação** ao DOM (disponibilização do pedido na mesa)
245247

246248
<IllustrationBlock sequential>
247-
<Illustration caption="Trigger" alt="React as a server in a restaurant, fetching orders from the users and delivering them to the Component Kitchen." src="/images/docs/illustrations/i_render-and-commit1.png" />
248-
<Illustration caption="Render" alt="The Card Chef gives React a fresh Card component." src="/images/docs/illustrations/i_render-and-commit2.png" />
249-
<Illustration caption="Commit" alt="React delivers the Card to the user at their table." src="/images/docs/illustrations/i_render-and-commit3.png" />
249+
<Illustration caption="Acionamento" alt="O React como um garçom em um restaurante, obtendo as solicitações dos usuários e entregando-as à cozinha dos componentes." src="/images/docs/illustrations/i_render-and-commit1.png" />
250+
<Illustration caption="Renderização" alt="O chef Card fornece ao React um componente de Card preparado na hora." src="/images/docs/illustrations/i_render-and-commit2.png" />
251+
<Illustration caption="Confirmação" alt="O React disponibiliza o Card para o usuário em sua mesa." src="/images/docs/illustrations/i_render-and-commit3.png" />
250252
</IllustrationBlock>
251253

252254
<LearnMore path="/learn/render-and-commit">
253255

254-
Read **[Render and Commit](/learn/render-and-commit)** to learn the lifecycle of a UI update.
256+
Leia **[Renderizar e Confirmar](/learn/render-and-commit)** para aprender sobre a atualização do ciclo de vida de uma UI.
255257

256258
</LearnMore>
257259

258-
## State as a snapshot {/*state-as-a-snapshot*/}
260+
## State como uma foto instantânea {/*state-as-a-snapshot*/}
259261

260-
Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first!
262+
Diferentemente de variáveis regulares do JavaScript, o state do React se comporta mais como uma foto instantânea. Definí-lo não altera a variável state que você já possui, mas ao invés disso, ativa uma nova renderização. Isso pode ser surpreendente no início!
261263

262264
```js
263265
console.log(count); // 0
264-
setCount(count + 1); // Request a re-render with 1
265-
console.log(count); // Still 0!
266+
setCount(count + 1); // Solicitação de uma nova renderização com 1
267+
console.log(count); // Ainda 0!
266268
```
267269

268-
This behavior helps you avoid subtle bugs. Here is a little chat app. Try to guess what happens if you press "Send" first and *then* change the recipient to Bob. Whose name will appear in the `alert` five seconds later?
270+
Este comportamento lhe ajuda a evitar bugs sutis. Aqui está um pequeno aplicativo de mensagens. Tente supor o que acontece se você pressionar "Send" primeiramente e depois alterar o destinatário para Bob. Qual nome aparecerá no `alert` após cinco segundos?
269271

270272
<Sandpack>
271273

@@ -314,13 +316,13 @@ label, textarea { margin-bottom: 10px; display: block; }
314316

315317
<LearnMore path="/learn/state-as-a-snapshot">
316318

317-
Read **[State as a Snapshot](/learn/state-as-a-snapshot)** to learn why state appears "fixed" and unchanging inside the event handlers.
319+
Leia **[State como uma Foto Instantânea](/learn/state-as-a-snapshot)** para aprender por que o state parece "fixo" e imutável dentro dos manipuladores de eventos.
318320

319321
</LearnMore>
320322

321-
## Queueing a series of state updates {/*queueing-a-series-of-state-updates*/}
323+
## Enfileirando uma série de atualizações no state {/*queueing-a-series-of-state-updates*/}
322324

323-
This component is buggy: clicking "+3" increments the score only once.
325+
Este componente contém bugs: clicar em "+3" incrementa a pontuação em apenas uma unidade.
324326

325327
<Sandpack>
326328

@@ -354,7 +356,7 @@ button { display: inline-block; margin: 10px; font-size: 20px; }
354356

355357
</Sandpack>
356358

357-
[State as a Snapshot](/learn/state-as-a-snapshot) explains why this is happening. Setting state requests a new re-render, but does not change it in the already running code. So `score` continues to be `0` right after you call `setScore(score + 1)`.
359+
[State como uma Foto Instantânea](/learn/state-as-a-snapshot) explica por que isso está acontecendo. Definir o state solicita uma nova renderização, mas não o altera no código já em execução. Então `score` continua a ser `0` logo depois de você chamar `setScore(score + 1)`.
358360

359361
```js
360362
console.log(score); // 0
@@ -366,7 +368,7 @@ setScore(score + 1); // setScore(0 + 1);
366368
console.log(score); // 0
367369
```
368370

369-
You can fix this by passing an *updater function* when setting state. Notice how replacing `setScore(score + 1)` with `setScore(s => s + 1)` fixes the "+3" button. This lets you queue multiple state updates.
371+
Você pode consertar isso passando uma *função de atualização* ao definir o state. Perceba como a substituição de `setScore(score + 1)` por `setScore(s => s + 1)` conserta o botão "+3". Isso lhe possibilita enfileirar múltiplas atualizações de state.
370372

371373
<Sandpack>
372374

@@ -402,15 +404,15 @@ button { display: inline-block; margin: 10px; font-size: 20px; }
402404

403405
<LearnMore path="/learn/queueing-a-series-of-state-updates">
404406

405-
Read **[Queueing a Series of State Updates](/learn/queueing-a-series-of-state-updates)** to learn how to queue a sequence of state updates.
407+
Leia **[Enfileirando uma Série de Atualizações no State](/learn/queueing-a-series-of-state-updates)** para aprender como enfileirar uma sequência de atualizações no state.
406408

407409
</LearnMore>
408410

409-
## Updating objects in state {/*updating-objects-in-state*/}
411+
## Atualizando objetos no state {/*updating-objects-in-state*/}
410412

411-
State can hold any kind of JavaScript value, including objects. But you shouldn't change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy.
413+
O state pode conter qualquer tipo de valor do JavaScript, inclusive objetos. Mas você não deve alterar diretamente os objetos e arrays que mantém no state do React. Em vez disso, quando desejar atualizar um objeto e array, você precisa criar um novo (ou fazer uma cópia de um existente) e, em seguida, definir o state para usar essa cópia.
412414

413-
Usually, you will use the `...` spread syntax to copy objects and arrays that you want to change. For example, updating a nested object could look like this:
415+
Normalmente, você utilizará a sintaxe de spread `...` para copiar objetos e arrays que deseja alterar. Por exemplo, a atualização de um objeto aninhado funcionaria assim:
414416

415417
<Sandpack>
416418

@@ -518,7 +520,7 @@ img { width: 200px; height: 200px; }
518520

519521
</Sandpack>
520522

521-
If copying objects in code gets tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer) to reduce repetitive code:
523+
Caso copiar objetos no código fique entediante, você pode utilizar uma biblioteca como [Immer](https://github.com/immerjs/use-immer) para reduzir o código repetitivo:
522524

523525
<Sandpack>
524526

@@ -633,13 +635,13 @@ img { width: 200px; height: 200px; }
633635

634636
<LearnMore path="/learn/updating-objects-in-state">
635637

636-
Read **[Updating Objects in State](/learn/updating-objects-in-state)** to learn how to update objects correctly.
638+
Leia **[Atualizando Objetos no State](/learn/updating-objects-in-state)** para aprender como atualizar objetos corretamente.
637639

638640
</LearnMore>
639641

640-
## Updating arrays in state {/*updating-arrays-in-state*/}
642+
## Atualizando arrays no state {/*updating-arrays-in-state*/}
641643

642-
Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array:
644+
Arrays são outro tipo de objetos mutáveis do JavaScript que podem ser armazenados no state. É recomendado que sejam tratados como somente leitura. Assim como objetos, ao atualizar um array armazenado no state, é necessário criar um novo (ou realizar a cópia de um existente), e depois definir o state para utilizar o novo array:
643645

644646
<Sandpack>
645647

@@ -705,7 +707,7 @@ function ItemList({ artworks, onToggle }) {
705707

706708
</Sandpack>
707709

708-
If copying arrays in code gets tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer) to reduce repetitive code:
710+
Caso copiar arrays no código fique entediante, você pode utilizar uma biblioteca como [Immer](https://github.com/immerjs/use-immer) para reduzir o código repetitivo:
709711

710712
<Sandpack>
711713

@@ -789,12 +791,12 @@ function ItemList({ artworks, onToggle }) {
789791

790792
<LearnMore path="/learn/updating-arrays-in-state">
791793

792-
Read **[Updating Arrays in State](/learn/updating-arrays-in-state)** to learn how to update arrays correctly.
794+
Leia **[Atualizando Arrays no State](/learn/updating-arrays-in-state)** para aprender como atualizar arrays corretamente.
793795

794796
</LearnMore>
795797

796-
## What's next? {/*whats-next*/}
798+
## O que vem a seguir? {/*whats-next*/}
797799

798-
Head over to [Responding to Events](/learn/responding-to-events) to start reading this chapter page by page!
800+
Vá até [Respondendo a Eventos](/learn/responding-to-events) para começar a ler este capítulo página por página!
799801

800-
Or, if you're already familiar with these topics, why not read about [Managing State](/learn/managing-state)?
802+
Ou, se você já está familiarizado com estes tópicos, por que não ler sobre [Gerenciando o Estado](/learn/managing-state)?

0 commit comments

Comments
 (0)