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/importing-and-exporting-components.md
+69-69Lines changed: 69 additions & 69 deletions
Original file line number
Diff line number
Diff line change
@@ -1,26 +1,26 @@
1
1
---
2
-
title: Importing and Exporting Components
2
+
title: Importando e Exportando Componentes
3
3
---
4
4
5
5
<Intro>
6
6
7
-
The magic of components lies in their reusability: you can create components that are composed of other components. But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places.
7
+
A magia dos componentes reside na sua habilidade de reutilização: você pode criar um componente que é composto por outros componentes. Mas conforme você aninha mais e mais componentes, faz sentido começar a dividi-los em arquivos diferentes. Isso permite que você mantenha seus arquivos fáceis de explorar e reutiliza-los em mais lugares.
8
8
9
9
</Intro>
10
10
11
11
<YouWillLearn>
12
12
13
-
*What a root component file is
14
-
*How to import and export a component
15
-
*When to use default and named imports and exports
16
-
*How to import and export multiple components from one file
17
-
*How to split components into multiple files
13
+
*O que é um arquivo de componente raiz
14
+
*Como importar e exportar um componente
15
+
*Quando usar importações e exportações padrão (`default`) e nomeada
16
+
*Como importar e exportar múltiplos componentes em um arquivo
17
+
*Como separar componentes em múltiplos arquivos
18
18
19
19
</YouWillLearn>
20
20
21
-
## The root component file {/*the-root-component-file*/}
21
+
## O arquivo de componente raiz {/*the-root-component-file*/}
22
22
23
-
In [Your First Component](/learn/your-first-component), you made a `Profile`component and a`Gallery`component that renders it:
23
+
Em [Seu Primeiro Componente](/learn/your-first-component), você criou um componente `Profile`e um componente`Gallery`que renderiza:
These currently live in a**root component file,**named`App.js`in this example. In [Create React App](https://create-react-app.dev/), your app lives in`src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page.
55
+
Atualmente, eles residem em um**arquivo de componente raiz,**chamado`App.js`nesse exemplo. Em [Criar Aplicação React](https://create-react-app.dev/), seu app reside em`src/App.js`. Dependendo da sua configuração, seu componente raiz pode estar em outro arquivo. Se você usar um framework com roteamento baseado em arquivo, como o Next.js, seu componente raiz será diferente para cada página.
56
56
57
-
## Exporting and importing a component {/*exporting-and-importing-a-component*/}
57
+
## Exportando e importando um componente {/*exporting-and-importing-a-component*/}
58
58
59
-
What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery`and`Profile`out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps:
59
+
E se você quiser mudar a tela inicial no futuro e colocar uma lista de livros de ciências lá? Ou colocar todos os perfis em outro lugar? Faz sentido mover `Gallery`e`Profile`para fora do arquivo do componente raiz. Isso os tornará mais modulares e reutilizáveis em outros arquivos. Você pode mover um componente em três etapas:
60
60
61
-
1.**Make**a new JS file to put the components in.
62
-
2.**Export**your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export)or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports).
63
-
3.**Import**it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults)or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports).
61
+
1.**Criar**um novo arquivo JS para colocar os componentes.
62
+
2.**Exportar**seu componente de função desse arquivo (usando exportações [padrão](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export)ou [nomeada](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports)).
63
+
3.**Importar**no arquivo onde você usará o componente (usando a técnica correspondente para importar exportações [padrão](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults)ou [nomeadas](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module)).
64
64
65
-
Here both`Profile`and`Gallery`have been moved out of `App.js`into a new file called`Gallery.js`. Now you can change `App.js`to import `Gallery`from`Gallery.js`:
65
+
Aqui, tanto`Profile`e`Gallery`foram movidos de `App.js`para um novo arquivo chamado`Gallery.js`. Agora você pode alterar o arquivo `App.js`para importar o componente `Gallery`de`Gallery.js`:
-Exporta o componente raiz `App`como uma **exportação padrão (default export).**
115
115
116
116
117
117
<Note>
118
118
119
-
You may encounter files that leave off the `.js`file extension like so:
119
+
Você pode encontrar arquivos que não possuem a extensão de arquivo `.js`da seguinte forma:
120
120
121
121
```js
122
122
importGalleryfrom'./Gallery';
123
123
```
124
124
125
-
Either`'./Gallery.js'`or`'./Gallery'`will work with React, though the former is closer to how [native ES Modules](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules)work.
125
+
Tanto`'./Gallery.js'`quanto`'./Gallery'`funcionarão com o React, embora o primeiro esteja mais próximo de como os [Módulos ES nativos](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules)funcionam.
126
126
127
127
</Note>
128
128
129
129
<DeepDive>
130
130
131
-
#### Default vs named exports {/*default-vs-named-exports*/}
131
+
#### Exportação padrão vs nomeada {/*default-vs-named-exports*/}
132
132
133
-
There are two primary ways to export values with JavaScript: default exports and named exports. So far, our examples have only used default exports. But you can use one or both of them in the same file. **A file can have no more than one _default_ export, but it can have as many _named_ exports as you like.**
133
+
Existem duas maneiras principais de exportar valores com JavaScript: exportações padrão e exportações nomeadas. Até agora, nossos exemplos usaram apenas exportações padrão. Mas você pode usar um ou ambos no mesmo arquivo. **Um arquivo não pode ter mais de uma exportação _padrão_, mas pode ter quantas exportações _nomeadas_ você desejar.**
134
134
135
-

135
+

136
136
137
-
How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track:
137
+
A forma como você exporta seu componente determina como você deve importá-lo. Você receberá um erro se tentar importar uma exportação padrão da mesma forma que faria com uma exportação nomeada! Este gráfico pode ajudá-lo a acompanhar:
138
138
139
-
|Syntax | Export statement | Import statement |
140
-
| -----------|-----------| -----------|
141
-
|Default|`export default function Button() {}`|`import Button from './Button.js';`|
142
-
|Named |`export function Button() {}`|`import { Button } from './Button.js';`|
139
+
|Sintase | Declaração de exportação| Declaração de importação|
|Padrão|`export default function Button() {}`|`import Button from './Button.js';`|
142
+
|Nomeada|`export function Button() {}`|`import { Button } from './Button.js';`|
143
143
144
-
When you write a _default_ import, you can put any name you want after `import`. For example, you could write`import Banana from './Button.js'`instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That's why they are called _named_ imports!
144
+
Quando você escreve uma importação _padrão_, você pode colocar o nome que quiser depois de `import`. Por exemplo, você poderia escrever`import Banana from './Button.js'`e ainda forneceria a mesma exportação padrão. Por outro lado, com importações nomeadas, o nome deve corresponder em ambos os lados. É por isso que eles são chamados de importações _nomeadas_!
145
145
146
-
**People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.**Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like`export default () => {}`, are discouraged because they make debugging harder.
146
+
**Os usuários costumam usar exportações padrão se o arquivo exportar apenas um componente e usar exportações nomeadas se exportar vários componentes e valores.**Independentemente de qual estilo de código você preferir, sempre forneça nomes significativos para as funções do componente e os arquivos que os contêm. Componentes sem nomes, como`export default () => {}`, são desencorajados porque dificultam a depuração.
147
147
148
148
</DeepDive>
149
149
150
-
## Exporting and importing multiple components from the same file {/*exporting-and-importing-multiple-components-from-the-same-file*/}
150
+
## Exportando e importando múltiplos componentes no mesmo arquivo {/*exporting-and-importing-multiple-components-from-the-same-file*/}
151
151
152
-
What if you want to show just one `Profile`instead of a gallery? You can export the `Profile` component, too. But`Gallery.js`already has a *default* export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a *named* export for `Profile`. **A file can only have one default export, but it can have numerous named exports!**
152
+
E se você quiser mostrar apenas um `Profile`em vez de uma galeria? Você também pode exportar o componente `Profile`. Mas`Gallery.js`já tem uma exportação *padrão* e você não pode ter _duas_ exportações padrão. Você poderia criar um novo arquivo com uma exportação padrão ou adicionar uma exportação *nomeada* para `Profile`. **Um arquivo pode ter apenas uma exportação padrão, mas pode ter várias exportações nomeadas!**
153
153
154
154
<Note>
155
155
156
-
To reduce the potential confusion between default and named exports, some teams choose to only stick to one style (default or named), or avoid mixing them in a single file. Do what works best for you!
156
+
Para reduzir a confusão potencial entre exportações padrão e nomeadas, algumas equipes optam por manter apenas um estilo (padrão ou nomeado) ou evitar misturá-los em um único arquivo. Faça o que for melhor para você!
157
157
158
158
</Note>
159
159
160
-
First, **export**`Profile`from`Gallery.js`using a named export (no `default` keyword):
160
+
Primeiro, **exporte**`Profile`de`Gallery.js`usando uma exportação nomeada (sem a palavra-chave `default`):
161
161
162
162
```js
163
163
exportfunctionProfile() {
164
164
// ...
165
165
}
166
166
```
167
167
168
-
Then, **import**`Profile`from`Gallery.js`to`App.js`using a named import (with the curly braces):
168
+
Então, **importe**`Profile`de`Gallery.js`para`App.js`usando uma importação nomeada (com chaves):
Now`Gallery.js`contains two exports: a default`Gallery`export, and a named`Profile`export. `App.js`imports both of them. Try editing`<Profile />`to`<Gallery />`and back in this example:
182
+
Agora`Gallery.js`contém duas exportações: uma exportação`Gallery`padrão e uma exportação`Profile`nomeada. `App.js`importa ambos. Tente editar`<Profile />`para`<Gallery />`e vice-versa neste exemplo:
-Exporta o componente raiz `App`como uma **exportação padrão.**
234
234
235
235
<Recap>
236
236
237
-
On this page you learned:
237
+
Nessa pagina você aprendeu:
238
238
239
-
*What a root component file is
240
-
*How to import and export a component
241
-
*When and how to use default and named imports and exports
242
-
*How to export multiple components from the same file
239
+
*O que é um arquivo de componente raiz
240
+
*Como importar e exportar um componente
241
+
*Quando e como usar importações e exportações padrão e nomeada
242
+
*Como exportar múltiplos componentes em um arquivo
243
243
244
244
</Recap>
245
245
246
246
247
247
248
248
<Challenges>
249
249
250
-
#### Split the components further {/*split-the-components-further*/}
250
+
#### Divida os componentes ainda mais {/*split-the-components-further*/}
251
251
252
-
Currently, `Gallery.js`exports both `Profile`and`Gallery`, which is a bit confusing.
252
+
Atualmente, `Gallery.js`exporta `Profile`e`Gallery`, o que é um pouco confuso.
253
253
254
-
Move the `Profile`component to its own `Profile.js`, and then change the `App`component to render both `<Profile />`and`<Gallery />`one after another.
254
+
Mova o componente `Profile`para seu próprio `Profile.js` e, em seguida, altere o componente `App`para renderizar `<Profile />`e`<Gallery />`um após o outro.
255
255
256
-
You may use either a default or a named export for `Profile`, but make sure that you use the corresponding import syntax in both `App.js`and`Gallery.js`! You can refer to the table from the deep dive above:
256
+
Você pode usar uma exportação padrão ou nomeada para `Profile`, mas certifique-se de usar a sintaxe de importação correspondente tanto em `App.js`e`Gallery.js`! Você pode consultar a tabela abaixo:
257
257
258
-
|Syntax | Export statement | Import statement |
259
-
| -----------|-----------| -----------|
260
-
|Default|`export default function Button() {}`|`import Button from './Button.js';`|
261
-
|Named |`export function Button() {}`|`import { Button } from './Button.js';`|
258
+
|Sintase | Declaração de exportação| Declaração de importação|
0 commit comments