diff --git a/src/content/learn/adding-interactivity.md b/src/content/learn/adding-interactivity.md index a7c851141..882c40f06 100644 --- a/src/content/learn/adding-interactivity.md +++ b/src/content/learn/adding-interactivity.md @@ -1,30 +1,30 @@ --- -title: Adding Interactivity +title: Adicionando Interatividade --- -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. +Algumas coisas na tela são atualizadas em resposta à entrada do usuário. Por exemplo, clicar em uma galeria de imagens troca a imagem ativa. No React, dados que mudam ao longo do tempo são chamados de *estado.* Você pode adicionar estado a qualquer componente e atualizá-lo conforme necessário. Neste capítulo, você aprenderá a escrever componentes que lidam com interações, atualizam seu estado e exibem diferentes saídas ao longo do tempo. -* [How to handle user-initiated events](/learn/responding-to-events) -* [How to make components "remember" information with state](/learn/state-a-components-memory) -* [How React updates the UI in two phases](/learn/render-and-commit) -* [Why state doesn't update right after you change it](/learn/state-as-a-snapshot) -* [How to queue multiple state updates](/learn/queueing-a-series-of-state-updates) -* [How to update an object in state](/learn/updating-objects-in-state) -* [How to update an array in state](/learn/updating-arrays-in-state) +* [Como lidar com eventos iniciados pelo usuário](/learn/responding-to-events) +* [Como fazer componentes "lembrar" informações com estado](/learn/state-a-components-memory) +* [Como o React atualiza a UI em duas fases](/learn/render-and-commit) +* [Por que o estado não é atualizado logo após você alterá-lo](/learn/state-as-a-snapshot) +* [Como enfileirar múltiplas atualizações de estado](/learn/queueing-a-series-of-state-updates) +* [Como atualizar um objeto no estado](/learn/updating-objects-in-state) +* [Como atualizar um array no estado](/learn/updating-arrays-in-state) -## Responding to events {/*responding-to-events*/} +## Respondendo a eventos {/*responding-to-events*/} -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. +O React permite que você adicione *manipuladores de eventos* ao seu JSX. Manipuladores de eventos são suas próprias funções que serão acionadas em resposta a interações do usuário, como clicar, passar o mouse, focar em entradas de formulário e assim por diante. -Built-in components like ` ); @@ -68,22 +68,22 @@ button { margin-right: 10px; } -Read **[Responding to Events](/learn/responding-to-events)** to learn how to add event handlers. +Leia **[Respondendo a Eventos](/learn/responding-to-events)** para aprender como adicionar manipuladores de eventos. -## State: a component's memory {/*state-a-components-memory*/} +## Estado: a memória de um componente {/*state-a-components-memory*/} -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.* +Componentes frequentemente precisam mudar o que está na tela como resultado de uma interação. Digitar no formulário deve atualizar o campo de entrada, clicar em "próximo" em um carrossel de imagens deve mudar qual imagem está sendo exibida, clicar em "comprar" coloca um produto no carrinho de compras. Componentes precisam "lembrar" coisas: o valor atual de entrada, a imagem atual, o carrinho de compras. No React, esse tipo de memória específica do componente é chamado de *estado.* -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. +Você pode adicionar estado a um componente com um Hook [`useState`](/apis/usestate). Hooks são funções especiais que permitem que seus componentes utilizem recursos do React (o estado é um desses recursos). O Hook `useState` permite que você declare uma variável de estado. Ele recebe o estado inicial e retorna um par de valores: o estado atual e uma função definidora de estado que permite que você o atualize. ```js const [index, setIndex] = useState(0); const [showMore, setShowMore] = useState(false); ``` -Here is how an image gallery uses and updates state on click: +Aqui está como uma galeria de imagens utiliza e atualiza o estado ao clicar: @@ -112,17 +112,17 @@ export default function Gallery() { return ( <>

{sculpture.name} - by {sculpture.artist} + por {sculpture.artist}

- ({index + 1} of {sculptureList.length}) + ({index + 1} de {sculptureList.length})

{showMore &&

{sculpture.description}

} -Read **[State: A Component's Memory](/learn/state-a-components-memory)** to learn how to remember a value and update it on interaction. +Leia **[Estado: A Memória de Um Componente](/learn/state-a-components-memory)** para aprender como lembrar um valor e atualizá-lo na interação. -## Render and commit {/*render-and-commit*/} +## Renderizar e confirmar {/*render-and-commit*/} -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. +Antes que seus componentes sejam exibidos na tela, eles devem ser renderizados pelo React. Compreender as etapas desse processo ajudará você a pensar sobre como seu código é executado e explicar seu comportamento. -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: +Imagine que seus componentes são cozinheiros na cozinha, montando pratos saborosos a partir de ingredientes. Nesse cenário, o React é o garçom que faz os pedidos dos clientes e traz a eles as suas encomendas. Esse processo de solicitar e servir a UI tem três etapas: -1. **Triggering** a render (delivering the diner's order to the kitchen) -2. **Rendering** the component (preparing the order in the kitchen) -3. **Committing** to the DOM (placing the order on the table) +1. **Acionar** uma renderização (entregar o pedido do cliente à cozinha) +2. **Renderizar** o componente (preparar o pedido na cozinha) +3. **Confirmar** ao DOM (colocar o pedido na mesa) - - - + + + -Read **[Render and Commit](/learn/render-and-commit)** to learn the lifecycle of a UI update. +Leia **[Renderizar e Confirmar](/learn/render-and-commit)** para aprender sobre o ciclo de vida de uma atualização de UI. -## State as a snapshot {/*state-as-a-snapshot*/} +## Estado como um instantâneo {/*state-as-a-snapshot*/} -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! +Diferente de variáveis regulares do JavaScript, o estado do React se comporta mais como um instantâneo. Alterá-lo não muda a variável de estado que você já tem, mas sim aciona uma nova renderização. Isso pode ser surpreendente a princípio! ```js console.log(count); // 0 -setCount(count + 1); // Request a re-render with 1 -console.log(count); // Still 0! +setCount(count + 1); // Solicitar uma nova renderização com 1 +console.log(count); // Ainda 0! ``` -This behavior help 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? +Esse comportamento ajuda você a evitar bugs sutis. Aqui está um pequeno aplicativo de bate-papo. Tente adivinhar o que acontece se você pressionar "Enviar" primeiro e *depois* mudar o destinatário para Bob. De quem o nome aparecerá no `alert` cinco segundos depois? @@ -274,19 +274,19 @@ import { useState } from 'react'; export default function Form() { const [to, setTo] = useState('Alice'); - const [message, setMessage] = useState('Hello'); + const [message, setMessage] = useState('Olá'); function handleSubmit(e) { e.preventDefault(); setTimeout(() => { - alert(`You said ${message} to ${to}`); + alert(`Você disse ${message} para ${to}`); }, 5000); } return (