Skip to content

Commit f729af3

Browse files
florenciasilvacarburo
authored andcommitted
Spanish translation of faq-functions (#124)
1 parent 25e4e67 commit f729af3

File tree

1 file changed

+70
-70
lines changed

1 file changed

+70
-70
lines changed

content/docs/faq-functions.md

Lines changed: 70 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
---
2-
id: faq-functions
3-
title: Passing Functions to Components
2+
id: faq-funciones
3+
title: Pasando Funciones a Componentes
44
permalink: docs/faq-functions.html
55
layout: docs
66
category: FAQ
77
---
88

9-
### How do I pass an event handler (like onClick) to a component? {#how-do-i-pass-an-event-handler-like-onclick-to-a-component}
9+
### ¿Cómo puedo pasar un controlador de eventos (como onClick) a un componente? {#how-do-i-pass-an-event-handler-like-onclick-to-a-component}
1010

11-
Pass event handlers and other functions as props to child components:
11+
Pasa controladores de eventos y otras funciones como props a componentes hijos:
1212

1313
```jsx
1414
<button onClick={this.handleClick}>
1515
```
1616

17-
If you need to have access to the parent component in the handler, you also need to bind the function to the component instance (see below).
17+
Si necesitas tener acceso al componente padre dentro del evento, también debes enlazar la funciones a la instancia del componente (ver abajo).
1818

19-
### How do I bind a function to a component instance? {#how-do-i-bind-a-function-to-a-component-instance}
19+
### ¿Cómo enlazo una función a la instancia de un componente? {#how-do-i-bind-a-function-to-a-component-instance}
2020

21-
There are several ways to make sure functions have access to component attributes like `this.props` and `this.state`, depending on which syntax and build steps you are using.
21+
Hay varias maneras de asegurarte que las funciones tengan acceso a los atributos del componente como `this.props` y `this.state`, dependiendo de que tipo de sintaxis o
2222

23-
#### Bind in Constructor (ES2015) {#bind-in-constructor-es2015}
23+
#### Enlazar dentro del Constructor (ES2015) {#bind-in-constructor-es2015}
2424

2525
```jsx
2626
class Foo extends Component {
@@ -29,71 +29,71 @@ class Foo extends Component {
2929
this.handleClick = this.handleClick.bind(this);
3030
}
3131
handleClick() {
32-
console.log('Click happened');
32+
console.log('Se hizo click');
3333
}
3434
render() {
35-
return <button onClick={this.handleClick}>Click Me</button>;
35+
return <button onClick={this.handleClick}>Clickéame</button>;
3636
}
3737
}
3838
```
3939

40-
#### Class Properties (Stage 3 Proposal) {#class-properties-stage-3-proposal}
40+
#### Propiedades de las Clases (Propuesta de etapa 3) {#class-properties-stage-3-proposal}
4141

4242
```jsx
4343
class Foo extends Component {
44-
// Note: this syntax is experimental and not standardized yet.
44+
// Nota: esta sintaxis es experimental y todavía no está estandarizada.
4545
handleClick = () => {
46-
console.log('Click happened');
46+
console.log('Se hizo click');
4747
}
4848
render() {
49-
return <button onClick={this.handleClick}>Click Me</button>;
49+
return <button onClick={this.handleClick}>Clickéame</button>;
5050
}
5151
}
5252
```
5353

54-
#### Bind in Render {#bind-in-render}
54+
#### Enlazar en la renderización {#bind-in-render}
5555

5656
```jsx
5757
class Foo extends Component {
5858
handleClick() {
59-
console.log('Click happened');
59+
console.log('Se hizo click');
6060
}
6161
render() {
62-
return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
62+
return <button onClick={this.handleClick.bind(this)}>Clickéame</button>;
6363
}
6464
}
6565
```
6666

67-
>**Note:**
67+
>**Nota:**
6868
>
69-
>Using `Function.prototype.bind` in render creates a new function each time the component renders, which may have performance implications (see below).
69+
> Al usar `Function.prototype.bind` dentro de la renderización se crea una nueva función cada vez que el componente se renderiza, lo cual podría implicar problemas de rendimiento (ver abajo).
7070
71-
#### Arrow Function in Render {#arrow-function-in-render}
71+
#### Funciones Flecha en renderización {#arrow-function-in-render}
7272

7373
```jsx
7474
class Foo extends Component {
7575
handleClick() {
76-
console.log('Click happened');
76+
console.log('Se hizo click');
7777
}
7878
render() {
79-
return <button onClick={() => this.handleClick()}>Click Me</button>;
79+
return <button onClick={() => this.handleClick()}>Clickéame</button>;
8080
}
8181
}
8282
```
8383

84-
>**Note:**
84+
>**Nota:**
8585
>
86-
>Using an arrow function in render creates a new function each time the component renders, which may have performance implications (see below).
86+
>Usar una función flecha en el renderizado crea una nueva función cada vez que se renderiza el componente, lo cual podría implicar problemas de rendimiento (ver abajo)
8787
88-
### Is it OK to use arrow functions in render methods? {#is-it-ok-to-use-arrow-functions-in-render-methods}
88+
### ¿Está bien utilizar funciones flecha en los métodos de renderizado? {#is-it-ok-to-use-arrow-functions-in-render-methods}
8989

90-
Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.
90+
Generalmente hablando, si está bien y normalmente es la forma más fácil de pasar parámetros a funciones.
9191

92-
If you do have performance issues, by all means, optimize!
92+
Si tienes problemas de rendimiento, ¡no dudes en optimizar!
9393

94-
### Why is binding necessary at all? {#why-is-binding-necessary-at-all}
94+
### ¿Por qué tiene que ser necesario enlazar? {#why-is-binding-necessary-at-all}
9595

96-
In JavaScript, these two code snippets are **not** equivalent:
96+
En JavaScript, estos dos fragmentos de código **no** son equivalentes.
9797

9898
```js
9999
obj.method();
@@ -104,50 +104,50 @@ var method = obj.method;
104104
method();
105105
```
106106

107-
Binding methods helps ensure that the second snippet works the same way as the first one.
107+
Los métodos de enlace nos aseguran que el segundo fragmento funcione de la misma manera que el primero.
108108

109-
With React, typically you only need to bind the methods you *pass* to other components. For example, `<button onClick={this.handleClick}>` passes `this.handleClick` so you want to bind it. However, it is unnecessary to bind the `render` method or the lifecycle methods: we don't pass them to other components.
109+
Con React, normalmente solo necesitamos enlazar los métodos que *pasamos* a otros componentes. Por ejemplo: `<button onClick={this.handleClick}>` pasa `this.handleClick` por ende, se debería enlazar. Sin embargo, es innecesario enlazar el método `render` o los métodos de ciclo de vida: no los pasamos a otros componentes.
110+
111+
[Este artículo creado por Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) explica a detalle que es enlazar, y como funcionan las funciones en JavaScript.
110112

111-
[This post by Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) explains what binding is, and how functions work in JavaScript, in detail.
113+
### ¿Por qué mi función está siendo llamada cada vez que mi componente renderiza? {#why-is-my-function-being-called-every-time-the-component-renders}
112114

113-
### Why is my function being called every time the component renders? {#why-is-my-function-being-called-every-time-the-component-renders}
114-
115-
Make sure you aren't _calling the function_ when you pass it to the component:
115+
Asegúrate que no estés _llamando la función_ cuando la pases al componente:
116116

117117
```jsx
118118
render() {
119-
// Wrong: handleClick is called instead of passed as a reference!
120-
return <button onClick={this.handleClick()}>Click Me</button>
119+
// Incorrecto: ¡Se llama a handleClick en vez de ser pasado como una referencia!
120+
return <button onClick={this.handleClick()}>Clickéame!</button>
121121
}
122122
```
123123

124-
Instead, *pass the function itself* (without parens):
124+
En lugar de eso, *pasa la función como tal* (sin los paréntesis)
125125

126126
```jsx
127127
render() {
128-
// Correct: handleClick is passed as a reference!
129-
return <button onClick={this.handleClick}>Click Me</button>
128+
// Correcto: handleClick se pasa como una referencia!
129+
return <button onClick={this.handleClick}>Clickéame</button>
130130
}
131131
```
132132

133-
### How do I pass a parameter to an event handler or callback? {#how-do-i-pass-a-parameter-to-an-event-handler-or-callback}
133+
### ¿Cómo paso un parámetro a un controlador de eventos o callback? {#how-do-i-pass-a-parameter-to-an-event-handler-or-callback}
134134

135-
You can use an arrow function to wrap around an event handler and pass parameters:
135+
Puedes utilizar funciones flecha para envolver un controlador de eventos y pasar parámetros:
136136

137137
```jsx
138138
<button onClick={() => this.handleClick(id)} />
139139
```
140140

141-
This is equivalent to calling `.bind`:
141+
Esto es lo equivalente de llamar `.bind`:
142142

143143
```jsx
144144
<button onClick={this.handleClick.bind(this, id)} />
145145
```
146146

147-
#### Example: Passing params using arrow functions {#example-passing-params-using-arrow-functions}
147+
#### Ejemplo: Pasar parámetros utilizando función flecha {#example-passing-params-using-arrow-functions}
148148

149149
```jsx
150-
const A = 65 // ASCII character code
150+
const A = 65 // código ASCII del carácter.
151151

152152
class Alphabet extends React.Component {
153153
constructor(props) {
@@ -178,12 +178,12 @@ class Alphabet extends React.Component {
178178
}
179179
```
180180

181-
#### Example: Passing params using data-attributes {#example-passing-params-using-data-attributes}
181+
#### Ejemplo: Pasando parámetros usando data-attributes {#example-passing-params-using-data-attributes}
182182

183-
Alternately, you can use DOM APIs to store data needed for event handlers. Consider this approach if you need to optimize a large number of elements or have a render tree that relies on React.PureComponent equality checks.
183+
Alternativamente, puedes utilizar APIs del DOM para guardar los datos que necesitan los controladores de eventos. Considera esta propuesta si necesitas optimizar una gran cantidad de elementos o tu árbol de renderizado depende de las verificaciones de igualdad de React.PureComponent.
184184

185185
```jsx
186-
const A = 65 // ASCII character code
186+
const A = 65 // código ASCII del carácter
187187

188188
class Alphabet extends React.Component {
189189
constructor(props) {
@@ -218,23 +218,23 @@ class Alphabet extends React.Component {
218218
}
219219
```
220220

221-
### How can I prevent a function from being called too quickly or too many times in a row? {#how-can-i-prevent-a-function-from-being-called-too-quickly-or-too-many-times-in-a-row}
221+
### ¿Cómo puede prevenir que una función sea llamada muy rápidamente o muchas veces seguidas? {#how-can-i-prevent-a-function-from-being-called-too-quickly-or-too-many-times-in-a-row}
222222

223-
If you have an event handler such as `onClick` or `onScroll` and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be done by using:
223+
Si tienes un controlador de eventos como `onClick` o `onScroll` y quieres prevenir que un *callback* sea disparado antes de tiempo, puedes limitar la tasa en la cual este *callback* es ejecutado. Se puede lograr usando:
224224

225-
- **throttling**: sample changes based on a time based frequency (eg [`_.throttle`](https://lodash.com/docs#throttle))
226-
- **debouncing**: publish changes after a period of inactivity (eg [`_.debounce`](https://lodash.com/docs#debounce))
227-
- **`requestAnimationFrame` throttling**: sample changes based on [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) (eg [`raf-schd`](https://github.com/alexreardon/raf-schd))
225+
- **throttle**: regula los cambios siguiendo una frecuencia basada en el tiempo (ej. [`_.throttle`](https://lodash.com/docs#throttle))
226+
- **debounce**: publica cambios después de un periodo de inactividad (ej. [`_.debounce`](https://lodash.com/docs#debounce))
227+
- **throttle con `requestAnimationFrame`**: regula los cambios en base a [`requestAnimationFrame`](https://developer.mozilla.org/es/docs/Web/API/Window/requestAnimationFrame) (ej [`raf-schd`](https://github.com/alexreardon/raf-schd))
228228

229-
See [this visualization](http://demo.nimius.net/debounce_throttle/) for a comparison of `throttle` and `debounce` functions.
229+
Mira [esta visualización](http://demo.nimius.net/debounce_throttle/) para ver la comparación entre las funciones `throttle` y `debounce`.
230230

231-
> Note:
231+
> Nota:
232232
>
233-
> `_.debounce`, `_.throttle` and `raf-schd` provide a `cancel` method to cancel delayed callbacks. You should either call this method from `componentWillUnmount` _or_ check to ensure that the component is still mounted within the delayed function.
233+
>`_.debounce`, `_.throttle` y `raf-schd` proporcionan el método `cancel` para cancelar *callbacks* retrasados. Puedes llamar este método dentro de `componentWillUnmount` _o_ corrobora que el componente sigue montado dentro de la función retrasada.
234234
235235
#### Throttle {#throttle}
236236

237-
Throttling prevents a function from being called more than once in a given window of time. The example below throttles a "click" handler to prevent calling it more than once per second.
237+
*Throttle* previene que una función sea llamada más de una vez según el tiempo determinado. El ejemplo que se encuentra debajo regula un controlador de evento tipo click para prevenir que se llame más de una vez por segundo.
238238

239239
```jsx
240240
import throttle from 'lodash.throttle';
@@ -262,7 +262,7 @@ class LoadMoreButton extends React.Component {
262262

263263
#### Debounce {#debounce}
264264

265-
Debouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called. This can be useful when you have to perform some expensive calculation in response to an event that might dispatch rapidly (eg scroll or keyboard events). The example below debounces text input with a 250ms delay.
265+
*Debounce* asegura que una función no va a ser ejecutada hasta que cierta cantidad de tiempo haya pasado desde la última vez que fue llamada. Esto puede ser muy útil cuando tienes que realizar operaciones demandantes como respuesta de un evento que puede ejecutarse muy rápido (ejemplo eventos de scroll o teclado). El siguiente ejemplo hace *debounce* de una entrada de texto con un demora de 250ms.
266266

267267
```jsx
268268
import debounce from 'lodash.debounce';
@@ -290,9 +290,9 @@ class Searchbox extends React.Component {
290290
}
291291

292292
handleChange(e) {
293-
// React pools events, so we read the value before debounce.
294-
// Alternately we could call `event.persist()` and pass the entire event.
295-
// For more info see reactjs.org/docs/events.html#event-pooling
293+
// React reune a los eventos, por ende leemos su valor antes del debounce
294+
// Alternativamente, podemos llamar `event.persist()` y pasa todo el evento.
295+
// Para mas información acerca de éste tema reactjs.org/docs/events.html#event-pooling
296296
this.emitChangeDebounced(e.target.value);
297297
}
298298

@@ -304,11 +304,11 @@ class Searchbox extends React.Component {
304304

305305
#### `requestAnimationFrame` throttling {#requestanimationframe-throttling}
306306

307-
[`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) is a way of queuing a function to be executed in the browser at the optimal time for rendering performance. A function that is queued with `requestAnimationFrame` will fire in the next frame. The browser will work hard to ensure that there are 60 frames per second (60 fps). However, if the browser is unable to it will naturally *limit* the amount of frames in a second. For example, a device might only be able to handle 30 fps and so you will only get 30 frames in that second. Using `requestAnimationFrame` for throttling is a useful technique in that it prevents you from doing more than 60 updates in a second. If you are doing 100 updates in a second this creates additional work for the browser that the user will not see anyway.
307+
[`requestAnimationFrame`](https://developer.mozilla.org/es/docs/Web/API/Window/requestAnimationFrame) es una forma de poner una función en cola para ser ejecutada por el navegador en un tiempo óptimo para el rendimiento del renderizado. Una función en cola con `requestAnimationFrame` va a dispararse en el siguiente cuadro. El navegador se va a encargar de que hayan 60 cuadros por segundo (60fps). Sin embargo, si el navegador no puede, el mismo navegador naturalmente va a limitar la cantida de cuadros por segundo. Por ejemplo, un dispositivo podría solo manejar 30 fps, por ende, solo tendrás 30 cuadros por segundo. Usando `requestAnimationFrame` para throttle es una técnica muy útil ya que previene que tú mismo generes más de 60 actualizaciones por segundo. Si estás generando 100 actualizaciones por segundo, puedes crear esfuerzo adicional para el navegador que el usuario de todas formas no va a poder apreciar.
308308

309-
>**Note:**
309+
>**Nota:**
310310
>
311-
>Using this technique will only capture the last published value in a frame. You can see an example of how this optimization works on [`MDN`](https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
311+
>Usando esta técnica podemos capturar el último valor capturado en un cuadro. Puedes ver a un ejemplo de como funciona este tipo de optimización en [`MDN`](https://developer.mozilla.org/es/docs/Web/Events/scroll)
312312
313313
```jsx
314314
import rafSchedule from 'raf-schd';
@@ -319,20 +319,20 @@ class ScrollListener extends React.Component {
319319

320320
this.handleScroll = this.handleScroll.bind(this);
321321

322-
// Create a new function to schedule updates.
322+
// Crea una nueva función para agendar actualizaciones
323323
this.scheduleUpdate = rafSchedule(
324324
point => this.props.onScroll(point)
325325
);
326326
}
327327

328328
handleScroll(e) {
329-
// When we receive a scroll event, schedule an update.
330-
// If we receive many updates within a frame, we'll only publish the latest value.
329+
// Cuando recibimos un evento tipo scroll, agenda una actualización.
330+
// Si recibimos muchas actualizaciones dentro de un cuadro, solo vamos a publicar el último valor
331331
this.scheduleUpdate({ x: e.clientX, y: e.clientY });
332332
}
333333

334334
componentWillUnmount() {
335-
// Cancel any pending updates since we're unmounting.
335+
// Cancela cualquier actualizacion pendiente ya que estamos 'unmounting'.
336336
this.scheduleUpdate.cancel();
337337
}
338338

@@ -349,6 +349,6 @@ class ScrollListener extends React.Component {
349349
}
350350
```
351351

352-
#### Testing your rate limiting {#testing-your-rate-limiting}
352+
#### Probando tu límite de cuadros {#testing-your-rate-limiting}
353353

354-
When testing your rate limiting code works correctly it is helpful to have the ability to fast forward time. If you are using [`jest`](https://facebook.github.io/jest/) then you can use [`mock timers`](https://facebook.github.io/jest/docs/en/timer-mocks.html) to fast forward time. If you are using `requestAnimationFrame` throttling then you may find [`raf-stub`](https://github.com/alexreardon/raf-stub) to be a useful tool to control the ticking of animation frames.
354+
Cuando probamos límites de cuadros de forma correcta, es muy útil tener la habilidad de adelantar el tiempo. Si estás utilizando [`jest`](https://facebook.github.io/jest/) puedes usar [`mock timers`](https://facebook.github.io/jest/docs/en/timer-mocks.html) para adelantar el tiempo. Si estás utilizando *throttle* con `requestAnimationFrame` podrías encontrar útil [`raf-stub`](https://github.com/alexreardon/raf-stub) para controlar la frecuencia de los cuadros de animación.

0 commit comments

Comments
 (0)