Skip to content

Commit 0bd5799

Browse files
Iago Brunoglaucia86
Iago Bruno
andcommitted
Translation of Forms page (reactjs#100)
* docs: Translation of Forms page * docs: Small corrections in "Forms" page Co-Authored-By: Halian Vilela <[email protected]> * docs: Removing accent from an example on the Forms page Co-Authored-By: glaucia86 <[email protected]>
1 parent 32df3c8 commit 0bd5799

File tree

1 file changed

+62
-62
lines changed

1 file changed

+62
-62
lines changed

content/docs/forms.md

Lines changed: 62 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
id: forms
3-
title: Forms
3+
title: Formulários
44
permalink: docs/forms.html
55
prev: lists-and-keys.html
66
next: lifting-state-up.html
@@ -9,27 +9,27 @@ redirect_from:
99
- "docs/forms-zh-CN.html"
1010
---
1111

12-
HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state. For example, this form in plain HTML accepts a single name:
12+
Os elementos de formulário HTML funcionam de maneira um pouco diferente de outros elementos DOM no React, porque os elementos de formulário mantêm naturalmente algum estado interno. Por exemplo, este formulário em HTML puro aceita um único nome:
1313

1414
```html
1515
<form>
1616
<label>
17-
Name:
17+
Nome:
1818
<input type="text" name="name" />
1919
</label>
20-
<input type="submit" value="Submit" />
20+
<input type="submit" value="Enviar" />
2121
</form>
2222
```
2323

24-
This form has the default HTML form behavior of browsing to a new page when the user submits the form. If you want this behavior in React, it just works. But in most cases, it's convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called "controlled components".
24+
Esse formulário tem o comportamento padrão do HTML de navegar para uma nova página quando o usuário enviar o formulário. Se você quer esse comportamento no React, ele simplesmente funciona. Mas na maioria dos casos, é conveniente ter uma função Javascript que manipula o envio de um formulário e tem acesso aos dados que o usuário digitou nos inputs. O modo padrão de fazer isso é com uma técnica chamada "componentes controlados" (controlled components).
2525

26-
## Controlled Components {#controlled-components}
26+
## Componentes Controlados (Controlled Components) {#controlled-components}
2727

28-
In HTML, form elements such as `<input>`, `<textarea>`, and `<select>` typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with [`setState()`](/docs/react-component.html#setstate).
28+
Em HTML, elementos de formulário como `<input>`, `<textarea>` e `<select>` normalmente mantêm seu próprio estado e o atualiza baseado na entrada do usuário. Em React, o estado mutável é normalmente mantido na propriedade state dos componentes e atualizado apenas com [`setState()`](/docs/react-component.html#setstate).
2929

30-
We can combine the two by making the React state be the "single source of truth". Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a "controlled component".
30+
Podemos combinar os dois fazendo o estado React ser a "única fonte da verdade". Assim, o componente React que renderiza um formulário também controla o que acontece nesse formulário nas entradas subsequentes do usuário. Um input cujo o valor é controlado pelo React dessa maneira é chamado de "componente controlado" (controlled component).
3131

32-
For example, if we want to make the previous example log the name when it is submitted, we can write the form as a controlled component:
32+
Por exemplo, se quisermos que o exemplo anterior registre o nome quando ele for enviado, podemos escrever o formulário como um componente controlado:
3333

3434
```javascript{4,10-12,24}
3535
class NameForm extends React.Component {
@@ -46,54 +46,54 @@ class NameForm extends React.Component {
4646
}
4747
4848
handleSubmit(event) {
49-
alert('A name was submitted: ' + this.state.value);
49+
alert('Um nome foi enviado: ' + this.state.value);
5050
event.preventDefault();
5151
}
5252
5353
render() {
5454
return (
5555
<form onSubmit={this.handleSubmit}>
5656
<label>
57-
Name:
57+
Nome:
5858
<input type="text" value={this.state.value} onChange={this.handleChange} />
5959
</label>
60-
<input type="submit" value="Submit" />
60+
<input type="submit" value="Enviar" />
6161
</form>
6262
);
6363
}
6464
}
6565
```
6666

67-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/VmmPgp?editors=0010)
67+
[**Experimente no CodePen**](https://codepen.io/gaearon/pen/VmmPgp?editors=0010)
6868

69-
Since the `value` attribute is set on our form element, the displayed value will always be `this.state.value`, making the React state the source of truth. Since `handleChange` runs on every keystroke to update the React state, the displayed value will update as the user types.
69+
Como o atributo `value` é definido no nosso `<input type="text">`, o valor exibido sempre será o mesmo de `this.state.value`, fazendo com que o estado do React seja a fonte da verdade. Como o `handleChange` é executado a cada tecla pressionada para atualizar o estado do React, o valor exibido será atualizado conforme o usuário digita.
7070

71-
With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input. For example, if we wanted to enforce that names are written with all uppercase letters, we could write `handleChange` as:
71+
Com um componente controlado, cada mutação de estado terá uma função de manipulação (handler function) associada. Isso faz com que seja simples modificar ou validar a entrada do usuário. Por exemplo, se quiséssemos impor que os nomes sejam escritos com todas as letras maiúsculas, poderíamos escrever `handleChange` como:
7272

7373
```javascript{2}
7474
handleChange(event) {
7575
this.setState({value: event.target.value.toUpperCase()});
7676
}
7777
```
7878

79-
## The textarea Tag {#the-textarea-tag}
79+
## Tag textarea {#the-textarea-tag}
8080

81-
In HTML, a `<textarea>` element defines its text by its children:
81+
Em HTML, o texto de um elemento <textarea> é definido por seus filhos:
8282

8383
```html
8484
<textarea>
85-
Hello there, this is some text in a text area
85+
Apenas algum texto em uma área de texto
8686
</textarea>
8787
```
8888

89-
In React, a `<textarea>` uses a `value` attribute instead. This way, a form using a `<textarea>` can be written very similarly to a form that uses a single-line input:
89+
Em React, em vez disso, o `<textarea>` usa um atributo `value`. Desta forma, um formulário usando um `<textarea>` pode ser escrito de forma muito semelhante a um formulário que usa um input de linha única:
9090

9191
```javascript{4-6,12-14,26}
9292
class EssayForm extends React.Component {
9393
constructor(props) {
9494
super(props);
9595
this.state = {
96-
value: 'Please write an essay about your favorite DOM element.'
96+
value: 'Por favor, escreva uma dissertação sobre o seu elemento DOM favorito.'
9797
};
9898
9999
this.handleChange = this.handleChange.bind(this);
@@ -105,46 +105,46 @@ class EssayForm extends React.Component {
105105
}
106106
107107
handleSubmit(event) {
108-
alert('An essay was submitted: ' + this.state.value);
108+
alert('Uma dissertação foi enviada: ' + this.state.value);
109109
event.preventDefault();
110110
}
111111
112112
render() {
113113
return (
114114
<form onSubmit={this.handleSubmit}>
115115
<label>
116-
Essay:
116+
Dissertação:
117117
<textarea value={this.state.value} onChange={this.handleChange} />
118118
</label>
119-
<input type="submit" value="Submit" />
119+
<input type="submit" value="Enviar" />
120120
</form>
121121
);
122122
}
123123
}
124124
```
125125

126-
Notice that `this.state.value` is initialized in the constructor, so that the text area starts off with some text in it.
126+
Observe que `this.state.value` é inicializado no construtor, para que o textarea comece com algum texto.
127127

128-
## The select Tag {#the-select-tag}
128+
## Tag select {#the-select-tag}
129129

130-
In HTML, `<select>` creates a drop-down list. For example, this HTML creates a drop-down list of flavors:
130+
Em HTML, `<select>` cria uma lista suspensa (drop-down). Por exemplo, esse HTML cria uma lista suspensa de sabores:
131131

132132
```html
133133
<select>
134-
<option value="grapefruit">Grapefruit</option>
135-
<option value="lime">Lime</option>
136-
<option selected value="coconut">Coconut</option>
137-
<option value="mango">Mango</option>
134+
<option value="laranja">Laranja</option>
135+
<option value="limao">Limão</option>
136+
<option selected value="coco">Coco</option>
137+
<option value="manga">Manga</option>
138138
</select>
139139
```
140140

141-
Note that the Coconut option is initially selected, because of the `selected` attribute. React, instead of using this `selected` attribute, uses a `value` attribute on the root `select` tag. This is more convenient in a controlled component because you only need to update it in one place. For example:
141+
Note que a opção "coco" é selecionada por padrão, por causa do atributo `selected`. Em React, em vez de usar este atributo `selected`, usa-se um atributo `value` na raiz da tag `select`. Isso é mais conveniente em um componente controlado, porque você só precisa atualizá-lo em um só lugar. Por exemplo:
142142

143143
```javascript{4,10-12,24}
144144
class FlavorForm extends React.Component {
145145
constructor(props) {
146146
super(props);
147-
this.state = {value: 'coconut'};
147+
this.state = {value: 'coco'};
148148
149149
this.handleChange = this.handleChange.bind(this);
150150
this.handleSubmit = this.handleSubmit.bind(this);
@@ -155,56 +155,56 @@ class FlavorForm extends React.Component {
155155
}
156156
157157
handleSubmit(event) {
158-
alert('Your favorite flavor is: ' + this.state.value);
158+
alert('Seu sabor favorito é: ' + this.state.value);
159159
event.preventDefault();
160160
}
161161
162162
render() {
163163
return (
164164
<form onSubmit={this.handleSubmit}>
165165
<label>
166-
Pick your favorite flavor:
166+
Escolha seu sabor favorito:
167167
<select value={this.state.value} onChange={this.handleChange}>
168-
<option value="grapefruit">Grapefruit</option>
169-
<option value="lime">Lime</option>
170-
<option value="coconut">Coconut</option>
171-
<option value="mango">Mango</option>
168+
<option value="laranja">Laranja</option>
169+
<option value="limao">Limão</option>
170+
<option value="coco">Coco</option>
171+
<option value="manga">Manga</option>
172172
</select>
173173
</label>
174-
<input type="submit" value="Submit" />
174+
<input type="submit" value="Enviar" />
175175
</form>
176176
);
177177
}
178178
}
179179
```
180180

181-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/JbbEzX?editors=0010)
181+
[**Experimente no CodePen**](https://codepen.io/gaearon/pen/JbbEzX?editors=0010)
182182

183-
Overall, this makes it so that `<input type="text">`, `<textarea>`, and `<select>` all work very similarly - they all accept a `value` attribute that you can use to implement a controlled component.
183+
No geral, isso faz com que as tags `<input type="text">`, `<textarea>` e `<select>` funcionem de forma muito semelhante - todos eles aceitam um atributo `value` que você pode usar para implementar um componente controlado.
184184

185-
> Note
185+
> Nota
186186
>
187-
> You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag:
187+
> Você pode passar um array para o atributo `value`, permitindo que você selecione várias opções em uma tag `select`:
188188
>
189189
>```js
190190
><select multiple={true} value={['B', 'C']}>
191191
>```
192192
193-
## The file input Tag {#the-file-input-tag}
193+
## Tag de entrada de arquivo (file input) {#the-file-input-tag}
194194
195-
In HTML, an `<input type="file">` lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the [File API](https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications).
195+
Em HTML, o `<input type="file">` permite ao usuário escolher um ou mais arquivos de seu dispositivo para serem enviados para um servidor ou manipulados por JavaScript através da [File API](https://developer.mozilla.org/pt-BR/docs/Web/API/File/Using_files_from_web_applications).
196196
197197
```html
198198
<input type="file" />
199199
```
200200
201-
Because its value is read-only, it is an **uncontrolled** component in React. It is discussed together with other uncontrolled components [later in the documentation](/docs/uncontrolled-components.html#the-file-input-tag).
201+
Como seu valor é de somente leitura, ele é um componente **não controlado** do React. Esses são discutidos junto a outros componentes não controlados [mais adiante na documentação](/docs/uncontrolled-components.html#the-file-input-tag).
202202

203-
## Handling Multiple Inputs {#handling-multiple-inputs}
203+
## Manipulando Múltiplos Inputs {#handling-multiple-inputs}
204204

205-
When you need to handle multiple controlled `input` elements, you can add a `name` attribute to each element and let the handler function choose what to do based on the value of `event.target.name`.
205+
Quando você precisa manipular múltiplos inputs controlados, você pode adicionar um atributo `name` a cada elemento e deixar a função manipuladora escolher o que fazer com base no valor de `event.target.name`.
206206

207-
For example:
207+
Por examplo:
208208

209209
```javascript{15,18,28,37}
210210
class Reservation extends React.Component {
@@ -232,7 +232,7 @@ class Reservation extends React.Component {
232232
return (
233233
<form>
234234
<label>
235-
Is going:
235+
Estão indo:
236236
<input
237237
name="isGoing"
238238
type="checkbox"
@@ -241,7 +241,7 @@ class Reservation extends React.Component {
241241
</label>
242242
<br />
243243
<label>
244-
Number of guests:
244+
Número de convidados:
245245
<input
246246
name="numberOfGuests"
247247
type="number"
@@ -254,31 +254,31 @@ class Reservation extends React.Component {
254254
}
255255
```
256256

257-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/wgedvV?editors=0010)
257+
[**Experimente no CodePen**](https://codepen.io/gaearon/pen/wgedvV?editors=0010)
258258

259-
Note how we used the ES6 [computed property name](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) syntax to update the state key corresponding to the given input name:
259+
Observe como usamos a sintaxe ES6 [nomes de propriedades computados] (https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Inicializador_Objeto#Nomes_de_propriedades_computados) para atualizar a chave de estado correspondente ao nome de entrada fornecido:
260260

261261
```js{2}
262262
this.setState({
263263
[name]: value
264264
});
265265
```
266266

267-
It is equivalent to this ES5 code:
267+
É equivalente a este código no ES5:
268268

269269
```js{2}
270270
var partialState = {};
271271
partialState[name] = value;
272272
this.setState(partialState);
273273
```
274274

275-
Also, since `setState()` automatically [merges a partial state into the current state](/docs/state-and-lifecycle.html#state-updates-are-merged), we only needed to call it with the changed parts.
275+
Além disso, como o `setState()` automaticamente [mescla um estado parcial ao estado atual](/docs/state-and-lifecycle.html#state-updates-are-merged), nós podemos chamá-lo apenas com as partes alteradas.
276276

277-
## Controlled Input Null Value {#controlled-input-null-value}
277+
## Valor Nulo em um Input Controlado {#controlled-input-null-value}
278278

279-
Specifying the value prop on a [controlled component](/docs/forms.html#controlled-components) prevents the user from changing the input unless you desire so. If you've specified a `value` but the input is still editable, you may have accidentally set `value` to `undefined` or `null`.
279+
A especificação de uma prop `value` em um [componente controlado](/docs/forms.html#controlled-components) impede que o usuário altere a entrada, a menos que você deseje. Se você especificou uma prop `value`, mas o input ainda é editável, você pode ter acidentalmente definido o `value` como `undefined` ou `null`.
280280

281-
The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
281+
O código a seguir demonstra isso. (O input é bloqueada no início, mas torna-se editável após um tempo.)
282282

283283
```javascript
284284
ReactDOM.render(<input value="hi" />, mountNode);
@@ -289,10 +289,10 @@ setTimeout(function() {
289289

290290
```
291291

292-
## Alternatives to Controlled Components {#alternatives-to-controlled-components}
292+
## Alternativas para Componentes Controlados {#alternatives-to-controlled-components}
293293

294-
It can sometimes be tedious to use controlled components, because you need to write an event handler for every way your data can change and pipe all of the input state through a React component. This can become particularly annoying when you are converting a preexisting codebase to React, or integrating a React application with a non-React library. In these situations, you might want to check out [uncontrolled components](/docs/uncontrolled-components.html), an alternative technique for implementing input forms.
294+
Às vezes pode ser tedioso usar componentes controlados, porque você precisa escrever um manipulador de eventos para cada maneira que seus dados podem mudar e canalizar todo o estado do input através de um componente React. Isso pode se tornar particularmente irritante quando você está convertendo uma base de código preexistente para o React ou integrando um aplicativo React com uma biblioteca que não seja baseado em React. Nessas situações, talvez você queira verificar os [componentes não controlados](/docs/uncontrolled-components.html), uma técnica alternativa para implementar formulários de entrada.
295295

296-
## Fully-Fledged Solutions {#fully-fledged-solutions}
296+
## Soluções Completas {#fully-fledged-solutions}
297297

298-
If you're looking for a complete solution including validation, keeping track of the visited fields, and handling form submission, [Formik](https://jaredpalmer.com/formik) is one of the popular choices. However, it is built on the same principles of controlled components and managing state — so don't neglect to learn them.
298+
Se você está procurando por uma solução completa, incluindo validação, manter o controle dos campos visualizados e lidar com o envio de formulários, o [Formik](https://jaredpalmer.com/formik) é uma das escolhas mais populares. No entanto, ele é construído sobre os mesmos princípios de componentes controlados e gerenciamento de estado - portanto, não negligencie o aprendizado desses conceitos.

0 commit comments

Comments
 (0)