-
Notifications
You must be signed in to change notification settings - Fork 291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Translate: handling events docs #77
Changes from 4 commits
29c2522
a9a902e
5629f93
0a43a36
c62b052
4b25b1d
604ea1c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,43 +1,43 @@ | ||||||
--- | ||||||
id: handling-events | ||||||
title: Handling Events | ||||||
title: Manejando Eventos | ||||||
permalink: docs/handling-events.html | ||||||
prev: state-and-lifecycle.html | ||||||
next: conditional-rendering.html | ||||||
redirect_from: | ||||||
- "docs/events-ko-KR.html" | ||||||
--- | ||||||
|
||||||
Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences: | ||||||
Manejar eventos con elementos de React es muy similar a manejar eventos con elementos del Dom.. Solo hay una diferencias de sintaxis: | ||||||
|
||||||
* React events are named using camelCase, rather than lowercase. | ||||||
* With JSX you pass a function as the event handler, rather than a string. | ||||||
* Los eventos de React se nombran usando camelCase, en vez de minúsculas. | ||||||
* En JSX se pasa la función como el manejador del evento, en vez de una cadena de texto. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could be:
Suggested change
Here are some words that you should consider to not translate, as string: https://github.com/reactjs/es.reactjs.org/blob/master/TRANSLATION.md |
||||||
|
||||||
For example, the HTML: | ||||||
Por ejemplo, el HTML: | ||||||
|
||||||
```html | ||||||
<button onclick="activateLasers()"> | ||||||
Activate Lasers | ||||||
</button> | ||||||
``` | ||||||
|
||||||
is slightly different in React: | ||||||
En React es algo diferente: | ||||||
|
||||||
```js{1} | ||||||
<button onClick={activateLasers}> | ||||||
Activate Lasers | ||||||
</button> | ||||||
``` | ||||||
|
||||||
Another difference is that you cannot return `false` to prevent default behavior in React. You must call `preventDefault` explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write: | ||||||
Otra diferencia es que en React no puedes retornar `false` para prevenir el comportamiento por defecto. Debes, explícitamente, llamar `preventDefault`. Por ejemplo, en un HTML plano, para prevenir el comportamiento por defecto de un enlace de abrir una nueva página, puedes escribir: | ||||||
|
||||||
```html | ||||||
<a href="#" onclick="console.log('The link was clicked.'); return false"> | ||||||
Click me | ||||||
</a> | ||||||
``` | ||||||
|
||||||
In React, this could instead be: | ||||||
En cambio en React, esto podría ser: | ||||||
|
||||||
```js{2-5,8} | ||||||
function ActionLink() { | ||||||
|
@@ -54,19 +54,19 @@ function ActionLink() { | |||||
} | ||||||
``` | ||||||
|
||||||
Here, `e` is a synthetic event. React defines these synthetic events according to the [W3C spec](https://www.w3.org/TR/DOM-Level-3-Events/), so you don't need to worry about cross-browser compatibility. See the [`SyntheticEvent`](/docs/events.html) reference guide to learn more. | ||||||
Aquí, `e` es un evento sintético. React define estos eventos sintéticos acorde a las [especificaciones W3C](https://www.w3.org/TR/DOM-Level-3-Events/), entonces no debes preocuparte por la compatibilidad a tráves de los navegadores. Mira la guía de referencia [`SyntheticEvent`](/docs/events.html) para aprender más. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What do you think about There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think |
||||||
|
||||||
When using React you should generally not need to call `addEventListener` to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered. | ||||||
Cuando estás utilizando React, generalmente, no debes llamar `addEventListener` para agregar manejadores de eventos a un elemento del DOM después de que este es creado. Por el contrario, solo debes proveer un manejador de eventos cuando el elemento es inicialmente renderizado. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think listeners aren't the same of handlers, so IMO you could change |
||||||
|
||||||
When you define a component using an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes), a common pattern is for an event handler to be a method on the class. For example, this `Toggle` component renders a button that lets the user toggle between "ON" and "OFF" states: | ||||||
Cuando defines un componente usando [clases de ES6](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Classes), un patrón muy común es que los manejadores de eventos sean un método de la clase. Por ejemplo, este componente `Toggle` renderiza un botón que permite al usuario cambiar el estado entre "PRENDIDO" y "APAGADO": | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IMO encendido sounds better than prendido. What do you think?
Suggested change
|
||||||
|
||||||
```js{6,7,10-14,18} | ||||||
class Toggle extends React.Component { | ||||||
constructor(props) { | ||||||
super(props); | ||||||
this.state = {isToggleOn: true}; | ||||||
|
||||||
// This binding is necessary to make `this` work in the callback | ||||||
// Esta ligadura es necesaria para hacer que `this` funcione en el callback | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What do you think about vínculo or enlace instead of ligadura? |
||||||
this.handleClick = this.handleClick.bind(this); | ||||||
} | ||||||
|
||||||
|
@@ -91,18 +91,18 @@ ReactDOM.render( | |||||
); | ||||||
``` | ||||||
|
||||||
[**Try it on CodePen**](http://codepen.io/gaearon/pen/xEmzGg?editors=0010) | ||||||
[**Pruébalo en CodePen**](http://codepen.io/gaearon/pen/xEmzGg?editors=0010) | ||||||
|
||||||
You have to be careful about the meaning of `this` in JSX callbacks. In JavaScript, class methods are not [bound](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind) by default. If you forget to bind `this.handleClick` and pass it to `onClick`, `this` will be `undefined` when the function is actually called. | ||||||
Tienes que tener mucho cuidado en cuanto al significado de `this` en los callbacks de JSX. En JavaScript, los métodos de clase no están [ligados](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind) por defecto. Si olvidas ligar `this.handleClick` y lo pasas a `onClick`, `this` sera `undefined` cuando se llame la función. | ||||||
|
||||||
This is not React-specific behavior; it is a part of [how functions work in JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Generally, if you refer to a method without `()` after it, such as `onClick={this.handleClick}`, you should bind that method. | ||||||
Esto no es un comportamiento especifico de React; esto hace parte de [como funcionan las funciones JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Generalmente, si refieres un método sin usar `()` después de este, tal como `onClick={this.handleClick}`, deberías ligar ese método. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe you could change Also IMO sounds better
than
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't know about |
||||||
|
||||||
If calling `bind` annoys you, there are two ways you can get around this. If you are using the experimental [public class fields syntax](https://babeljs.io/docs/plugins/transform-class-properties/), you can use class fields to correctly bind callbacks: | ||||||
Si te molesta llamar `bind`, existen dos maneras de evitarlo. Si usas la sintaxis experimental [campos publicos de clases](https://babeljs.io/docs/plugins/transform-class-properties/), puedes usar los campos de clases para ligar los callbacks correctamente: | ||||||
|
||||||
```js{2-6} | ||||||
class LoggingButton extends React.Component { | ||||||
// This syntax ensures `this` is bound within handleClick. | ||||||
// Warning: this is *experimental* syntax. | ||||||
// Esta sintaxis nos asegura que `this` esta ligado dentro de handleClick | ||||||
// Peligro: esto es una sintaxis *experimental* | ||||||
handleClick = () => { | ||||||
console.log('this is:', this); | ||||||
} | ||||||
|
@@ -117,9 +117,9 @@ class LoggingButton extends React.Component { | |||||
} | ||||||
``` | ||||||
|
||||||
This syntax is enabled by default in [Create React App](https://github.com/facebookincubator/create-react-app). | ||||||
|
||||||
If you aren't using class fields syntax, you can use an [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in the callback: | ||||||
Esta sintaxis está habilitada por defecto en [Create React App](https://github.com/facebookincubator/create-react-app). | ||||||
: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
Si no estas usando la sintaxis de campos publicos de clases, puedes usar [funciones flecha](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) en el callback: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
```js{7-9} | ||||||
class LoggingButton extends React.Component { | ||||||
|
@@ -128,7 +128,7 @@ class LoggingButton extends React.Component { | |||||
} | ||||||
|
||||||
render() { | ||||||
// This syntax ensures `this` is bound within handleClick | ||||||
// Esta sintaxis nos asegura que `this` esta ligado dentro de handleClick | ||||||
return ( | ||||||
<button onClick={(e) => this.handleClick(e)}> | ||||||
Click me | ||||||
|
@@ -138,17 +138,17 @@ class LoggingButton extends React.Component { | |||||
} | ||||||
``` | ||||||
|
||||||
The problem with this syntax is that a different callback is created each time the `LoggingButton` renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem. | ||||||
El problema con esta sintaxis es que un callback diferente es creado cada vez que `LogginButton` es renderizado. En la mayoría de los casos, esto está bien. Sin embargo, si este callback se pasa como una propiedad a componentes más bajos, estos componentes podría renderizarse nuevamente. Nosotros, generalmente, recomendamos ligar en el constructor o usar la sintaxis de campos de clases, para evitar esta clase de problemas de rendimiento. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
## Passing Arguments to Event Handlers {#passing-arguments-to-event-handlers} | ||||||
## Pasando Argumentos a un Manejador de Eventos {#passing-arguments-to-event-handlers} | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I suggest
Suggested change
|
||||||
|
||||||
Inside a loop it is common to want to pass an extra parameter to an event handler. For example, if `id` is the row ID, either of the following would work: | ||||||
Dentro de un bucle es muy común querer pasar un parámetro extra a un manejador de eventos. Por ejemplo, si `id` es el ID de una fila, cualquiera de los códigos a continuación podría funcionar: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I suggest
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IMHO, Maybe Hearing opinions. |
||||||
|
||||||
```js | ||||||
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> | ||||||
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> | ||||||
``` | ||||||
|
||||||
The above two lines are equivalent, and use [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and [`Function.prototype.bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) respectively. | ||||||
Las dos líneas anteriores son equivalentes, y utilizan [funciones flecha](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) y [`Function.prototype.bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) respectivamente. | ||||||
|
||||||
In both cases, the `e` argument representing the React event will be passed as a second argument after the ID. With an arrow function, we have to pass it explicitly, but with `bind` any further arguments are automatically forwarded. | ||||||
En ambos casos, el argumento `e` que representa el evento de React va a ser pasado como un segundo argumento después del ID. Con una función flecha, tenemos que pasarlo explícitamente, pero con `bind` cualquier argumento adicional es pasado automáticamente |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I suggest