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
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.
13
13
14
14
```html
15
15
<form>
16
16
<label>
17
-
Name:
17
+
Nombre:
18
18
<inputtype="text"name="name" />
19
19
</label>
20
-
<inputtype="submit"value="Submit" />
20
+
<inputtype="submit"value="Enviar" />
21
21
</form>
22
22
```
23
23
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".
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).
29
29
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".
31
31
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:
33
33
34
34
```javascript{4,10-12,24}
35
35
class NameForm extends React.Component {
@@ -46,54 +46,54 @@ class NameForm extends React.Component {
46
46
}
47
47
48
48
handleSubmit(event) {
49
-
alert('A name was submitted: ' + this.state.value);
49
+
alert('Un nombre fue suministrado: ' + this.state.value);
[**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)
68
68
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.
70
70
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:
In HTML, a `<textarea>`element defines its text by its children:
81
+
En HTML, el elemento `<textarea>`define su texto por sus hijos:
82
82
83
83
```html
84
84
<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
86
86
</textarea>
87
87
```
88
88
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:
90
90
91
91
```javascript{4-6,12-14,26}
92
92
class EssayForm extends React.Component {
93
93
constructor(props) {
94
94
super(props);
95
95
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.'
97
97
};
98
98
99
99
this.handleChange = this.handleChange.bind(this);
@@ -105,40 +105,40 @@ class EssayForm extends React.Component {
105
105
}
106
106
107
107
handleSubmit(event) {
108
-
alert('An essay was submitted: ' + this.state.value);
108
+
alert('Un ensayo fue enviado: ' + this.state.value);
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.
127
127
128
-
## The select Tag {#the-select-tag}
128
+
## La Etiqueta select {#the-select-tag}
129
129
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:
131
131
132
132
```html
133
133
<select>
134
-
<optionvalue="grapefruit">Grapefruit</option>
135
-
<optionvalue="lime">Lime</option>
136
-
<optionselectedvalue="coconut">Coconut</option>
134
+
<optionvalue="grapefruit">Toronja</option>
135
+
<optionvalue="lime">Lima</option>
136
+
<optionselectedvalue="coconut">Coco</option>
137
137
<optionvalue="mango">Mango</option>
138
138
</select>
139
139
```
140
140
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:
142
142
143
143
```javascript{4,10-12,24}
144
144
class FlavorForm extends React.Component {
@@ -155,56 +155,56 @@ class FlavorForm extends React.Component {
155
155
}
156
156
157
157
handleSubmit(event) {
158
-
alert('Your favorite flavor is: ' + this.state.value);
[**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)
182
182
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.
184
184
185
-
> Note
185
+
> Nota
186
186
>
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`:
188
188
>
189
189
>```js
190
190
><select multiple={true} value={['B', 'C']}>
191
191
>```
192
192
193
-
## The file input Tag {#the-file-input-tag}
193
+
## La Etiqueta file input {#the-file-input-tag}
194
194
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).
196
196
197
197
```html
198
198
<input type="file"/>
199
199
```
200
200
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).
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`.
206
206
207
-
For example:
207
+
Por ejemplo:
208
208
209
209
```javascript{15,18,28,37}
210
210
class Reservation extends React.Component {
@@ -232,7 +232,7 @@ class Reservation extends React.Component {
232
232
return (
233
233
<form>
234
234
<label>
235
-
Is going:
235
+
Va a ir:
236
236
<input
237
237
name="isGoing"
238
238
type="checkbox"
@@ -241,7 +241,7 @@ class Reservation extends React.Component {
241
241
</label>
242
242
<br />
243
243
<label>
244
-
Number of guests:
244
+
Número de Invitados:
245
245
<input
246
246
name="numberOfGuests"
247
247
type="number"
@@ -254,31 +254,30 @@ class Reservation extends React.Component {
254
254
}
255
255
```
256
256
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)
258
258
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*.
260
260
261
261
```js{2}
262
262
this.setState({
263
263
[name]: value
264
264
});
265
265
```
266
-
267
-
It is equivalent to this ES5 code:
266
+
Esto es equivalente a este código ES5:
268
267
269
268
```js{2}
270
269
var partialState = {};
271
270
partialState[name] = value;
272
271
this.setState(partialState);
273
272
```
274
273
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.
276
275
277
-
## Controlled Input Null Value {#controlled-input-null-value}
276
+
## Valor Nulo en un Input Controlado {#controlled-input-null-value}
278
277
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`.
280
279
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).
282
281
283
282
```javascript
284
283
ReactDOM.render(<input value="hi"/>, mountNode);
@@ -289,10 +288,10 @@ setTimeout(function() {
289
288
290
289
```
291
290
292
-
## Alternatives to Controlled Components {#alternatives-to-controlled-components}
291
+
## Alternativas a Componentes Controlados {#alternatives-to-controlled-components}
293
292
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.
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