You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/learn/adding-interactivity.md
+53-51Lines changed: 53 additions & 51 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,30 +1,30 @@
1
1
---
2
-
title: Adding Interactivity
2
+
title: Adicionando Interatividade
3
3
---
4
4
5
5
<Intro>
6
6
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.
8
8
9
9
</Intro>
10
10
11
11
<YouWillLearnisChapter={true}>
12
12
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)
20
20
21
21
</YouWillLearn>
22
22
23
-
## Responding to events {/*responding-to-events*/}
23
+
## Respondendo a eventos {/*responding-to-events*/}
24
24
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`.
26
26
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.
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.
72
72
73
73
</LearnMore>
74
74
75
-
## State: a component's memory {/*state-a-components-memory*/}
75
+
## State: A memória de um componente {/*state-a-components-memory*/}
76
76
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.*
78
78
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.
80
80
81
81
```js
82
82
const [index, setIndex] =useState(0);
83
83
const [showMore, setShowMore] =useState(false);
84
84
```
85
85
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:
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.
233
233
234
234
</LearnMore>
235
235
236
-
## Render and commit {/*render-and-commit*/}
236
+
## Renderizar e confirmar {/*render-and-commit*/}
237
237
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.
239
239
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.
241
241
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)
245
247
246
248
<IllustrationBlocksequential>
247
-
<Illustrationcaption="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
-
<Illustrationcaption="Render"alt="The Card Chef gives React a fresh Card component."src="/images/docs/illustrations/i_render-and-commit2.png" />
249
-
<Illustrationcaption="Commit"alt="React delivers the Card to the user at their table."src="/images/docs/illustrations/i_render-and-commit3.png" />
249
+
<Illustrationcaption="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
+
<Illustrationcaption="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
+
<Illustrationcaption="Confirmação"alt="O React disponibiliza o Card para o usuário em sua mesa."src="/images/docs/illustrations/i_render-and-commit3.png" />
250
252
</IllustrationBlock>
251
253
252
254
<LearnMorepath="/learn/render-and-commit">
253
255
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.
255
257
256
258
</LearnMore>
257
259
258
-
## State as a snapshot {/*state-as-a-snapshot*/}
260
+
## State como uma foto instantânea {/*state-as-a-snapshot*/}
259
261
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!
261
263
262
264
```js
263
265
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!
266
268
```
267
269
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?
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.
318
320
319
321
</LearnMore>
320
322
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*/}
322
324
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.
[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)`.
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.
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.
406
408
407
409
</LearnMore>
408
410
409
-
## Updating objects in state {/*updating-objects-in-state*/}
411
+
## Atualizando objetos no state {/*updating-objects-in-state*/}
410
412
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.
412
414
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:
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:
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.
637
639
638
640
</LearnMore>
639
641
640
-
## Updating arrays in state {/*updating-arrays-in-state*/}
642
+
## Atualizando arrays no state {/*updating-arrays-in-state*/}
641
643
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:
643
645
644
646
<Sandpack>
645
647
@@ -705,7 +707,7 @@ function ItemList({ artworks, onToggle }) {
705
707
706
708
</Sandpack>
707
709
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:
709
711
710
712
<Sandpack>
711
713
@@ -789,12 +791,12 @@ function ItemList({ artworks, onToggle }) {
789
791
790
792
<LearnMorepath="/learn/updating-arrays-in-state">
791
793
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.
793
795
794
796
</LearnMore>
795
797
796
-
## What's next? {/*whats-next*/}
798
+
## O que vem a seguir? {/*whats-next*/}
797
799
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!
799
801
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