Skip to content

Commit 157ef5a

Browse files
Darking360carburo
authored andcommitted
Translate: Basics > Forms (#132)
1 parent 7ef42b6 commit 157ef5a

File tree

1 file changed

+59
-60
lines changed

1 file changed

+59
-60
lines changed

content/docs/forms.md

Lines changed: 59 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
id: forms
3-
title: Forms
3+
title: Formularios
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+
Los elementos de formularios en HTML funcionan un poco diferente a otros elementos del DOM en React, debido a que los elementos de formularios conservan naturalmente algún estado interno. Por ejemplo, este formulario solamente en HTML, acepta un solo nombre.
1313

1414
```html
1515
<form>
1616
<label>
17-
Name:
17+
Nombre:
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+
Este formulario tiene el comportamiento predeterminado en HTML que consiste en navegar a una nueva página cuando el usuario envía el formulario. Si deseas este comportamiento en React, simplemente ya funciona así. Pero en la mayoría de casos, es conveniente tener una función en Javascript que se encargue del envío del formulario, y que tenga acceso a los datos que el usuario introdujo en el formulario. La forma predeterminada para conseguir esto es una técnica llamada "componentes controlados".
2525

26-
## Controlled Components {#controlled-components}
26+
## Componentes Controlados {#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+
En HTML, los elementos de formularios como los `<input>`, `<textarea>` y el `<select>` normalmente mantienen sus propios estados y los actualizan de acuerdo a la interacción del usuario. En React, el estado mutable es mantenido normalmente en la propiedad estado de los componentes, y solo se actualiza con [`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 ambos haciendo que el estado de React sea la "única fuente de la verdad". De esta manera, los componentes React que rendericen un formulario también controlan lo que pasa en ese formulario con las subsecuentes entradas del usuario. Un campo de un formulario cuyos valores son controlados por React de esta forma es denominado "componente controlado".
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 ejemplo, si queremos hacer que el ejemplo anterior muestre el nombre que esta siendo suministrado, podemos escribir el formulario como un 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('Un nombre fue suministrado: ' + this.state.value);
5050
event.preventDefault();
5151
}
5252
5353
render() {
5454
return (
5555
<form onSubmit={this.handleSubmit}>
5656
<label>
57-
Name:
57+
Nombre:
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+
[**Pruébalo en 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+
Ya que el atributo `value` es agregado en nuestro elemento del formulario, el valor mostrado siempre será el de `this.state.value`, haciendo que el estado de React sea la fuente de la verdad. Ya que `handleChange` corre cada vez que una tecla es oprimida para actualizar el estado de React, el valor mostrado será actualizado mientras que el usuario escribe.
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+
Con un componente controlado, toda mutación del estado tendrá asociada una función controlador. Esto hace más directo modificar o validar la entrada del usuario. Por ejemplo, si quisiéramos asegurar que los nombres sean escritos con todas las letras en mayúscula, podríamos escribir el `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+
## La Etiqueta textarea {#the-textarea-tag}
8080

81-
In HTML, a `<textarea>` element defines its text by its children:
81+
En HTML, el elemento `<textarea>` define su texto por sus hijos:
8282

8383
```html
8484
<textarea>
85-
Hello there, this is some text in a text area
85+
Hola, esto es un poco de texto dentro de un á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+
En React, un `<textarea>` utiliza un atributo `value` en su lugar. De esta manera, un formulario que hace uso de un `<textarea>` puede ser escrito de manera similar a un formulario que utiliza un campo en una sola línea:
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 escribe un ensayo sobre tu elemento del DOM favorito.'
9797
};
9898
9999
this.handleChange = this.handleChange.bind(this);
@@ -105,40 +105,40 @@ class EssayForm extends React.Component {
105105
}
106106
107107
handleSubmit(event) {
108-
alert('An essay was submitted: ' + this.state.value);
108+
alert('Un ensayo fue enviado: ' + this.state.value);
109109
event.preventDefault();
110110
}
111111
112112
render() {
113113
return (
114114
<form onSubmit={this.handleSubmit}>
115115
<label>
116-
Essay:
116+
Ensayo:
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+
Recuerda que `this.state.value` es inicializado en el constructor, de manera que el área de texto empiece con algo de texto.
127127

128-
## The select Tag {#the-select-tag}
128+
## La Etiqueta 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+
En HTML, `<select>` crea una lista desplegable. Por ejemplo, este HTML crea una lista desplegable 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>
134+
<option value="grapefruit">Toronja</option>
135+
<option value="lime">Lima</option>
136+
<option selected value="coconut">Coco</option>
137137
<option value="mango">Mango</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+
Ten en cuenta que la opción *Coco* es inicialmente seleccionada, debido al atributo `selected`. React, en lugar de utilizar el atributo `selected`, utiliza un atributo `value` en la raíz de la etiqueta `select`. Esto es más conveniente en un componente controlado debido a que solo necesitas actualizarlo en un solo lugar, por ejemplo:
142142

143143
```javascript{4,10-12,24}
144144
class FlavorForm extends React.Component {
@@ -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('Tu sabor favorito es: ' + 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+
Selecciona tu 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>
168+
<option value="grapefruit">Toronja</option>
169+
<option value="lime">Lima</option>
170+
<option value="coconut">Coco</option>
171171
<option value="mango">Mango</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+
[**Pruébalo en 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+
En resumen, esto hace que `<input type="text">`, `<textarea>`, y `<select>` trabajen de manera similar, todos aceptan un atributo `value` el cual puedes usar para implementar un 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+
> Puedes pasar un array al atributo `value`, permitiendo que selecciones múltiples opciones en una etiqueta `select`:
188188
>
189189
>```js
190190
><select multiple={true} value={['B', 'C']}>
191191
>```
192192
193-
## The file input Tag {#the-file-input-tag}
193+
## La Etiqueta 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+
En HTML, un `<input type="file">` permite que el usuario escoja uno o varios archivos de su dispositivo de almacenamiento para ser cargados a un servidor o ser manipulados por Javascript mediante el [API de Archivos](https://developer.mozilla.org/es/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+
Ya que su valor es solo de lectura, es un componente **no controlado** en React. Es explicado en detalle junto a otros componentes no controlados [más adelante en la documentación](/docs/uncontrolled-components.html#the-file-input-tag).
202202

203-
## Handling Multiple Inputs {#handling-multiple-inputs}
203+
## Manejando Múltiples 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+
Cuando necesitas manejar múltiples elementos `input` controlados, puedes agregar un atributo `name` a cada uno de los elementos y dejar que la función controladora decida que hacer basada en el valor de `event.target.name`.
206206

207-
For example:
207+
Por ejemplo:
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+
Va a ir:
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 Invitados:
245245
<input
246246
name="numberOfGuests"
247247
type="number"
@@ -254,31 +254,30 @@ class Reservation extends React.Component {
254254
}
255255
```
256256

257-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/wgedvV?editors=0010)
257+
[**Pruébalo en 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+
Ten en cuenta como utilizamos la sintaxis de la [propiedad *name* computada de ES6](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) para actualizar la clave del estado correspondiente al nombre del *input*.
260260

261261
```js{2}
262262
this.setState({
263263
[name]: value
264264
});
265265
```
266-
267-
It is equivalent to this ES5 code:
266+
Esto es equivalente a este código ES5:
268267

269268
```js{2}
270269
var partialState = {};
271270
partialState[name] = value;
272271
this.setState(partialState);
273272
```
274273

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.
274+
También, ya que `setState()` automáticamente [combina un estado parcial al estado actual](/docs/state-and-lifecycle.html#state-updates-are-merged), solamente necesitamos llamarlo con las partes que han cambiado.
276275

277-
## Controlled Input Null Value {#controlled-input-null-value}
276+
## Valor Nulo en un Input Controlado {#controlled-input-null-value}
278277

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`.
278+
Especificar la propiedad `value` en un [componente controlado](/docs/forms.html#controlled-components) evita que el usuario cambie la entrada a menos que así lo quiera. Si has especificado un `value` pero la entrada aún es editable, quizás agregaste accidentalmente al `value` un valor `undefined` o `null`.
280279

281-
The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
280+
El código a continuación demuestra esto. (El input está bloqueado en principio, pero se vuelve editable después de un corto retraso).
282281

283282
```javascript
284283
ReactDOM.render(<input value="hi" />, mountNode);
@@ -289,10 +288,10 @@ setTimeout(function() {
289288

290289
```
291290

292-
## Alternatives to Controlled Components {#alternatives-to-controlled-components}
291+
## Alternativas a Componentes Controlados {#alternatives-to-controlled-components}
293292

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.
293+
A veces puede ser tedioso usar componentes controlados, debido a que se necesita escribir un controlador de eventos para cada forma en la que tus datos puedan cambiar y agregarlos a todos en el estado del *input* a través del componente React. Esto puede volverse particularmente molesto cuando estás convirtiendo una base de código existente a React, o integrando una aplicación React con una biblioteca que no integra React. En estas situaciones, puede que quieras leer acerca de [componentes no controlados](/docs/uncontrolled-components.html), una técnica alternativa para implementar *inputs* en formularios.
295294

296-
## Fully-Fledged Solutions {#fully-fledged-solutions}
295+
## Soluciones Completas {#fully-fledged-solutions}
297296

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.
297+
Si lo que estás buscando es una solución completa incluyendo validación, tener en cuenta los campos visitados y manejar el envío del formulario, [Formik](https://jaredpalmer.com/formik) es una de las opciones populares. Sin embargo, está construido con los mismos principios de los componentes controlados y manejo de estado, así que no los dejes de aprender.

0 commit comments

Comments
 (0)