diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md index 822891e60..9bbdc2454 100644 --- a/src/content/learn/thinking-in-react.md +++ b/src/content/learn/thinking-in-react.md @@ -1,18 +1,18 @@ --- -title: Thinking in React +title: Pensando em React --- -React can change how you think about the designs you look at and the apps you build. When you build a user interface with React, you will first break it apart into pieces called *components*. Then, you will describe the different visual states for each of your components. Finally, you will connect your components together so that the data flows through them. In this tutorial, we’ll guide you through the thought process of building a searchable product data table with React. +O React pode mudar a maneira como você pensa sobre os designs que você vê e os aplicativos que você constrói. Ao construir uma interface de usuário com o React, você primeiro a dividirá em partes chamadas *componentes*. Em seguida, você descreverá os diferentes estados visuais para cada um de seus componentes. Finalmente, você conectará seus componentes para que os dados fluam através deles. Neste tutorial, guiaremos você pelo processo de pensamento de como construir uma tabela de dados de produto pesquisável com React. -## Start with the mockup {/*start-with-the-mockup*/} +## Comece com o mockup {/*start-with-the-mockup*/} -Imagine that you already have a JSON API and a mockup from a designer. +Imagine que você já tem uma API JSON e um mockup de um designer. -The JSON API returns some data that looks like this: +A API JSON retorna alguns dados que se parecem com isto: ```json [ @@ -25,25 +25,25 @@ The JSON API returns some data that looks like this: ] ``` -The mockup looks like this: +O mockup se parece com isto: -To implement a UI in React, you will usually follow the same five steps. +Para implementar uma UI em React, você geralmente seguirá as mesmas cinco etapas. -## Step 1: Break the UI into a component hierarchy {/*step-1-break-the-ui-into-a-component-hierarchy*/} +## Etapa 1: Divida a UI em uma hierarquia de componentes {/*step-1-break-the-ui-into-a-component-hierarchy*/} -Start by drawing boxes around every component and subcomponent in the mockup and naming them. If you work with a designer, they may have already named these components in their design tool. Ask them! +Comece desenhando caixas em torno de cada componente e subcomponente no mockup e dando nome a eles. Se você trabalha com um designer, ele já pode ter nomeado esses componentes em sua ferramenta de design. Pergunte a ele! -Depending on your background, you can think about splitting up a design into components in different ways: +Dependendo de sua experiência, você pode pensar em dividir um design em componentes de maneiras diferentes: -* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents. -* **CSS**--consider what you would make class selectors for. (However, components are a bit less granular.) -* **Design**--consider how you would organize the design's layers. +* **Programação**--use as mesmas técnicas para decidir se você deve criar uma nova função ou objeto. Uma dessas técnicas é o [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle), ou seja, um componente deve, idealmente, fazer apenas uma coisa. Se ele acabar crescendo, ele deve ser decomposto em componentes menores. +* **CSS**--considere para quais seletores de classe você faria. (No entanto, os componentes são um pouco menos granulares.) +* **Design**--considere como você organizaria as camadas do design. -If your JSON is well-structured, you'll often find that it naturally maps to the component structure of your UI. That's because UI and data models often have the same information architecture--that is, the same shape. Separate your UI into components, where each component matches one piece of your data model. +Se seu JSON estiver bem estruturado, você frequentemente descobrirá que ele mapeia naturalmente para a estrutura de componentes de sua UI. Isso ocorre porque a UI e os modelos de dados geralmente têm a mesma arquitetura de informações, ou seja, a mesma forma. Separe sua UI em componentes, onde cada componente corresponde a uma parte de seu modelo de dados. -There are five components on this screen: +Existem cinco componentes nesta tela: @@ -51,33 +51,33 @@ There are five components on this screen: -1. `FilterableProductTable` (grey) contains the entire app. -2. `SearchBar` (blue) receives the user input. -3. `ProductTable` (lavender) displays and filters the list according to the user input. -4. `ProductCategoryRow` (green) displays a heading for each category. -5. `ProductRow` (yellow) displays a row for each product. +1. `FilterableProductTable` (cinza) contém todo o aplicativo. +2. `SearchBar` (azul) recebe a entrada do usuário. +3. `ProductTable` (lavanda) exibe e filtra a lista de acordo com a entrada do usuário. +4. `ProductCategoryRow` (verde) exibe um cabeçalho para cada categoria. +5. `ProductRow` (amarelo) exibe uma linha para cada produto. -If you look at `ProductTable` (lavender), you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference, and you could go either way. For this example, it is a part of `ProductTable` because it appears inside the `ProductTable`'s list. However, if this header grows to be complex (e.g., if you add sorting), you can move it into its own `ProductTableHeader` component. +Se você olhar para `ProductTable` (lavanda), verá que o cabeçalho da tabela (contendo os rótulos "Name" e "Price") não é um componente próprio. Esta é uma questão de preferência, e você pode seguir qualquer caminho. Para este exemplo, ele faz parte do `ProductTable` porque aparece dentro da lista do `ProductTable`. No entanto, se este cabeçalho se tornar complexo (por exemplo, se você adicionar a classificação), você poderá movê-lo para seu próprio componente `ProductTableHeader`. -Now that you've identified the components in the mockup, arrange them into a hierarchy. Components that appear within another component in the mockup should appear as a child in the hierarchy: +Agora que você identificou os componentes no mockup, organize-os em uma hierarquia. Os componentes que aparecem dentro de outro componente no mockup devem aparecer como filhos na hierarquia: -* `FilterableProductTable` - * `SearchBar` - * `ProductTable` - * `ProductCategoryRow` - * `ProductRow` +* `FilterableProductTable` + * `SearchBar` + * `ProductTable` + * `ProductCategoryRow` + * `ProductRow` -## Step 2: Build a static version in React {/*step-2-build-a-static-version-in-react*/} +## Etapa 2: Crie uma versão estática em React {/*step-2-build-a-static-version-in-react*/} -Now that you have your component hierarchy, it's time to implement your app. The most straightforward approach is to build a version that renders the UI from your data model without adding any interactivity... yet! It's often easier to build the static version first and add interactivity later. Building a static version requires a lot of typing and no thinking, but adding interactivity requires a lot of thinking and not a lot of typing. +Agora que você tem sua hierarquia de componentes, é hora de implementar seu aplicativo. A abordagem mais direta é construir uma versão que renderiza a UI de seu modelo de dados sem adicionar nenhuma interatividade... ainda! Muitas vezes é mais fácil construir a versão estática primeiro e adicionar interatividade mais tarde. Construir uma versão estática requer muita digitação e nenhum pensamento, mas adicionar interatividade requer muito pensamento e pouca digitação. -To build a static version of your app that renders your data model, you'll want to build [components](/learn/your-first-component) that reuse other components and pass data using [props.](/learn/passing-props-to-a-component) Props are a way of passing data from parent to child. (If you're familiar with the concept of [state](/learn/state-a-components-memory), don't use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don't need it.) +Para construir uma versão estática de seu aplicativo que renderize seu modelo de dados, você desejará construir [componentes](/learn/your-first-component) que reutilizem outros componentes e passem dados usando [props.](/learn/passing-props-to-a-component) Props são uma maneira de passar dados do pai para o filho. (Se você estiver familiarizado com o conceito de [state](/learn/state-a-components-memory), não use state para construir esta versão estática. State é reservado apenas para interatividade, isto é, dados que mudam com o tempo. Como esta é uma versão estática do aplicativo, você não precisa dele.) -You can either build "top down" by starting with building the components higher up in the hierarchy (like `FilterableProductTable`) or "bottom up" by working from components lower down (like `ProductRow`). In simpler examples, it’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up. +Você pode construir "top down", começando com a construção dos componentes mais altos na hierarquia (como `FilterableProductTable`) ou "bottom up", trabalhando a partir de componentes mais baixos (como `ProductRow`). Em exemplos mais simples, geralmente é mais fácil ir de cima para baixo, e em projetos maiores, é mais fácil ir de baixo para cima. @@ -195,85 +195,85 @@ td { -(If this code looks intimidating, go through the [Quick Start](/learn/) first!) +(Se este código parecer intimidador, analise o [Início Rápido](/learn/) primeiro!) -After building your components, you'll have a library of reusable components that render your data model. Because this is a static app, the components will only return JSX. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. This is called _one-way data flow_ because the data flows down from the top-level component to the ones at the bottom of the tree. +Depois de construir seus componentes, você terá uma biblioteca de componentes reutilizáveis que renderiza seu modelo de dados. Como este é um aplicativo estático, os componentes retornarão apenas JSX. O componente no topo da hierarquia (`FilterableProductTable`) aceitará seu modelo de dados como uma prop. Isso é chamado de _fluxo de dados unidirecional_ porque os dados fluem de cima para baixo do componente de nível superior para os da parte inferior da árvore. -At this point, you should not be using any state values. That’s for the next step! +Neste ponto, você não deve estar usando nenhum valor de state. Isso é para a próxima etapa! -## Step 3: Find the minimal but complete representation of UI state {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/} +## Etapa 3: Encontre a representação mínima, mas completa, do state da UI {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/} -To make the UI interactive, you need to let users change your underlying data model. You will use *state* for this. +Para tornar a UI interativa, você precisa permitir que os usuários alterem seu modelo de dados subjacente. Você usará *state* para isso. -Think of state as the minimal set of changing data that your app needs to remember. The most important principle for structuring state is to keep it [DRY (Don't Repeat Yourself).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Figure out the absolute minimal representation of the state your application needs and compute everything else on-demand. For example, if you're building a shopping list, you can store the items as an array in state. If you want to also display the number of items in the list, don't store the number of items as another state value--instead, read the length of your array. +Pense no state como o conjunto mínimo de dados em mudança que seu aplicativo precisa lembrar. O princípio mais importante para estruturar o state é mantê-lo [DRY (Don't Repeat Yourself)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Descubra a representação mínima absoluta do state que seu aplicativo precisa e calcule todo o resto sob demanda. Por exemplo, se você estiver construindo uma lista de compras, poderá armazenar os itens como um array em state. Se você também quiser exibir o número de itens na lista, não armazene o número de itens como outro valor de state - em vez disso, leia o comprimento do seu array. -Now think of all of the pieces of data in this example application: +Agora pense em todos os dados de exemplo neste aplicativo: -1. The original list of products -2. The search text the user has entered -3. The value of the checkbox -4. The filtered list of products +1. A lista original de produtos +2. O texto de pesquisa que o usuário inseriu +3. O valor da checkbox +4. A lista filtrada de produtos -Which of these are state? Identify the ones that are not: +Quais destes são state? Identifique aqueles que não são: -* Does it **remain unchanged** over time? If so, it isn't state. -* Is it **passed in from a parent** via props? If so, it isn't state. -* **Can you compute it** based on existing state or props in your component? If so, it *definitely* isn't state! +* Ele **permanece inalterado** ao longo do tempo? Se sim, não é state. +* Ele é **passado de um pai** via props? Se sim, não é state. +* Você **pode calculá-lo** com base no state ou props existentes em seu componente? Se sim, *definitivamente* não é state! -What's left is probably state. +O que sobra é provavelmente state. -Let's go through them one by one again: +Vamos repassar um por um novamente: -1. The original list of products is **passed in as props, so it's not state.** -2. The search text seems to be state since it changes over time and can't be computed from anything. -3. The value of the checkbox seems to be state since it changes over time and can't be computed from anything. -4. The filtered list of products **isn't state because it can be computed** by taking the original list of products and filtering it according to the search text and value of the checkbox. +1. A lista original de produtos é **passada como props, então não é state.** +2. O texto de pesquisa parece ser state, pois muda com o tempo e não pode ser calculado a partir de nada. +3. O valor da checkbox parece ser state, pois muda com o tempo e não pode ser calculado a partir de nada. +4. A lista filtrada de produtos **não é state porque pode ser calculada** pegando a lista original de produtos e filtrando-a de acordo com o texto de pesquisa e o valor da checkbox. -This means only the search text and the value of the checkbox are state! Nicely done! +Isso significa que somente o texto de pesquisa e o valor da checkbox são state! Muito bom! #### Props vs State {/*props-vs-state*/} -There are two types of "model" data in React: props and state. The two are very different: +Existem dois tipos de dados de "modelo" no React: props e state. Os dois são muito diferentes: -* [**Props** are like arguments you pass](/learn/passing-props-to-a-component) to a function. They let a parent component pass data to a child component and customize its appearance. For example, a `Form` can pass a `color` prop to a `Button`. -* [**State** is like a component’s memory.](/learn/state-a-components-memory) It lets a component keep track of some information and change it in response to interactions. For example, a `Button` might keep track of `isHovered` state. +* [**Props** são como argumentos que você passa](/learn/passing-props-to-a-component)para uma função. Eles permitem que um componente pai passe dados para um componente filho e personalize sua aparência. Por exemplo, um `Form` pode passar uma prop `color` para um `Button`. +* [**State** é como a memória de um componente.](/learn/state-a-components-memory) Ele permite que um componente acompanhe algumas informações e as altere em resposta a interações. Por exemplo, um `Button` pode acompanhar o state `isHovered`. -Props and state are different, but they work together. A parent component will often keep some information in state (so that it can change it), and *pass it down* to child components as their props. It's okay if the difference still feels fuzzy on the first read. It takes a bit of practice for it to really stick! +Props e state são diferentes, mas funcionam em conjunto. Um componente pai geralmente manterá algumas informações em state (para que possa alterá-las) e *passará para baixo* para componentes filhos como suas props. Está tudo bem se a diferença ainda parecer confusa na primeira leitura. Leva um pouco de prática para realmente fixar! -## Step 4: Identify where your state should live {/*step-4-identify-where-your-state-should-live*/} +## Etapa 4: Identifique onde seu state deve viver {/*step-4-identify-where-your-state-should-live*/} -After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or *owns* the state. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what state. This can be challenging if you’re new to this concept, but you can figure it out by following these steps! +Depois de identificar os dados mínimos de state do seu aplicativo, você precisa identificar qual componente é responsável por alterar este state, ou *possui* o state. Lembre-se: o React usa fluxo de dados unidirecional, passando dados pela hierarquia de componentes do componente pai para o componente filho. Pode não ser imediatamente claro qual componente deve possuir qual state. Isso pode ser desafiador se você é novo nesse conceito, mas você pode descobrir seguindo estas etapas! -For each piece of state in your application: +Para cada parte do state em seu aplicativo: -1. Identify *every* component that renders something based on that state. -2. Find their closest common parent component--a component above them all in the hierarchy. -3. Decide where the state should live: - 1. Often, you can put the state directly into their common parent. - 2. You can also put the state into some component above their common parent. - 3. If you can't find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common parent component. +1. Identifique *todos* os componentes que renderizam algo com base nesse state. +2. Encontre o componente pai comum mais próximo - um componente acima de todos eles na hierarquia. +3. Decida onde o state deve viver: + 1. Frequentemente, você pode colocar o state diretamente em seu pai comum. + 2. Você também pode colocar o state em algum componente acima de seu pai comum. + 3. Se você não conseguir encontrar um componente onde faça sentido possuir o state, crie um novo componente apenas para manter o state e adicione-o em algum lugar na hierarquia acima do componente pai comum. -In the previous step, you found two pieces of state in this application: the search input text, and the value of the checkbox. In this example, they always appear together, so it makes sense to put them into the same place. +Na etapa anterior, você encontrou duas partes de state neste aplicativo: o texto de entrada da pesquisa e o valor da checkbox. Neste exemplo, eles sempre aparecem juntos, então faz sentido colocá-los no mesmo lugar. -Now let's run through our strategy for them: +Agora, vamos executar nossa estratégia para eles: -1. **Identify components that use state:** - * `ProductTable` needs to filter the product list based on that state (search text and checkbox value). - * `SearchBar` needs to display that state (search text and checkbox value). -2. **Find their common parent:** The first parent component both components share is `FilterableProductTable`. -3. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`. +1. **Identifique os componentes que usam o state:** + * `ProductTable` precisa filtrar a lista de produtos com base nesse state (texto de pesquisa e valor da checkbox). + * `SearchBar` precisa exibir esse state (texto de pesquisa e valor da checkbox). +2. **Encontre seu pai comum:** O primeiro componente pai que ambos os componentes compartilham é `FilterableProductTable`. +3. **Decida onde o state vive**: Manteremos o texto do filtro e os valores do state verificados em `FilterableProductTable`. -So the state values will live in `FilterableProductTable`. +Portanto, os valores de state viverão em `FilterableProductTable`. -Add state to the component with the [`useState()` Hook.](/reference/react/useState) Hooks are special functions that let you "hook into" React. Add two state variables at the top of `FilterableProductTable` and specify their initial state: +Adicione state ao componente com o [`useState()` Hook.](/reference/react/useState) Hooks são funções especiais que permitem que você "se conecte" ao React. Adicione duas variáveis de state na parte superior de `FilterableProductTable` e especifique seu estado inicial: ```js function FilterableProductTable({ products }) { @@ -281,7 +281,7 @@ function FilterableProductTable({ products }) { const [inStockOnly, setInStockOnly] = useState(false); ``` -Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as props: +Em seguida, passe `filterText` e `inStockOnly` para `ProductTable` e `SearchBar` como props: ```js
@@ -295,7 +295,7 @@ Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as p
``` -You can start seeing how your application will behave. Edit the `filterText` initial value from `useState('')` to `useState('fruit')` in the sandbox code below. You'll see both the search input text and the table update: +Você pode começar a ver como seu aplicativo se comportará. Edite o valor inicial `filterText` de `useState('')` para `useState('fruit')` no código do sandbox abaixo. Você verá o texto de entrada da pesquisa e a atualização da tabela: @@ -437,15 +437,15 @@ td { -Notice that editing the form doesn't work yet. There is a console error in the sandbox above explaining why: +Observe que editar o formulário ainda não funciona. Há um erro de console no sandbox acima explicando o porquê: -You provided a \`value\` prop to a form field without an \`onChange\` handler. This will render a read-only field. +Você forneceu uma prop \`value\` para um campo de formulário sem um manipulador \`onChange\`. Isso renderizará um campo somente leitura. -In the sandbox above, `ProductTable` and `SearchBar` read the `filterText` and `inStockOnly` props to render the table, the input, and the checkbox. For example, here is how `SearchBar` populates the input value: +No sandbox acima, `ProductTable` e `SearchBar` leem as props `filterText` e `inStockOnly` para renderizar a tabela, a entrada e a checkbox. Por exemplo, aqui está como `SearchBar` preenche o valor da entrada: ```js {1,6} function SearchBar({ filterText, inStockOnly }) { @@ -457,16 +457,15 @@ function SearchBar({ filterText, inStockOnly }) { placeholder="Search..."/> ``` -However, you haven't added any code to respond to the user actions like typing yet. This will be your final step. +No entanto, você ainda não adicionou nenhum código para responder às ações do usuário, como digitar. Esta será sua etapa final. +## Etapa 5: Adicione o fluxo de dados inverso {/*step-5-add-inverse-data-flow*/} -## Step 5: Add inverse data flow {/*step-5-add-inverse-data-flow*/} +Atualmente, seu aplicativo renderiza corretamente com as props e o state fluindo pela hierarquia. Mas para alterar o state de acordo com a entrada do usuário, você precisará suportar dados que fluem de outra maneira: os componentes do formulário na parte inferior da hierarquia precisam atualizar o state em `FilterableProductTable`. -Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`. +O React torna este fluxo de dados explícito, mas requer um pouco mais de digitação do que a associação de dados bidirecional. Se você tentar digitar ou marcar a caixa no exemplo acima, verá que o React ignora sua entrada. Isso é intencional. Ao escrever ``, você definiu a prop `value`da `input` para ser sempre igual ao state `filterText` passado de `FilterableProductTable`. Como o state `filterText` nunca é definido, a entrada nunca muda. -React makes this data flow explicit, but it requires a little more typing than two-way data binding. If you try to type or check the box in the example above, you'll see that React ignores your input. This is intentional. By writing ``, you've set the `value` prop of the `input` to always be equal to the `filterText` state passed in from `FilterableProductTable`. Since `filterText` state is never set, the input never changes. - -You want to make it so whenever the user changes the form inputs, the state updates to reflect those changes. The state is owned by `FilterableProductTable`, so only it can call `setFilterText` and `setInStockOnly`. To let `SearchBar` update the `FilterableProductTable`'s state, you need to pass these functions down to `SearchBar`: +Você deseja fazer com que, sempre que o usuário alterar as entradas do formulário, o state seja atualizado para refletir essas alterações. O state é propriedade de `FilterableProductTable`, portanto, somente ele pode chamar `setFilterText` e `setInStockOnly`. Para permitir que o `SearchBar` atualize o state do `FilterableProductTable`, você precisa passar essas funções para `SearchBar`: ```js {2,3,10,11} function FilterableProductTable({ products }) { @@ -482,7 +481,7 @@ function FilterableProductTable({ products }) { onInStockOnlyChange={setInStockOnly} /> ``` -Inside the `SearchBar`, you will add the `onChange` event handlers and set the parent state from them: +Dentro do `SearchBar`, você adicionará os manipuladores de eventos `onChange` e definirá o state pai a partir deles: ```js {4,5,13,19} function SearchBar({ @@ -506,7 +505,7 @@ function SearchBar({ onChange={(e) => onInStockOnlyChange(e.target.checked)} ``` -Now the application fully works! +Agora o aplicativo funciona totalmente! @@ -656,8 +655,8 @@ td { -You can learn all about handling events and updating state in the [Adding Interactivity](/learn/adding-interactivity) section. +Você pode aprender tudo sobre lidar com eventos e atualizar o state na seção [Adicionando Interatividade](/learn/adding-interactivity). -## Where to go from here {/*where-to-go-from-here*/} +## Para onde ir a partir daqui {/*where-to-go-from-here*/} -This was a very brief introduction to how to think about building components and applications with React. You can [start a React project](/learn/installation) right now or [dive deeper on all the syntax](/learn/describing-the-ui) used in this tutorial. +Esta foi uma breve introdução sobre como pensar em construir componentes e aplicativos com o React. Você pode [iniciar um projeto React](/learn/installation) agora ou [aprofundar em toda a sintaxe](/learn/describing-the-ui) usada neste tutorial. \ No newline at end of file