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
Copy file name to clipboardExpand all lines: content/docs/faq-functions.md
+70-70Lines changed: 70 additions & 70 deletions
Original file line number
Diff line number
Diff line change
@@ -1,26 +1,26 @@
1
1
---
2
-
id: faq-functions
3
-
title: Passing Functions to Components
2
+
id: faq-funciones
3
+
title: Pasando Funciones a Componentes
4
4
permalink: docs/faq-functions.html
5
5
layout: docs
6
6
category: FAQ
7
7
---
8
8
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}
10
10
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:
12
12
13
13
```jsx
14
14
<button onClick={this.handleClick}>
15
15
```
16
16
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).
18
18
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}
20
20
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
22
22
23
-
#### Bind in Constructor (ES2015) {#bind-in-constructor-es2015}
23
+
#### Enlazar dentro del Constructor (ES2015) {#bind-in-constructor-es2015}
>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).
70
70
71
-
#### Arrow Function in Render {#arrow-function-in-render}
71
+
#### Funciones Flecha en renderización {#arrow-function-in-render}
>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)
87
87
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}
89
89
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.
91
91
92
-
If you do have performance issues, by all means, optimize!
92
+
Si tienes problemas de rendimiento, ¡no dudes en optimizar!
93
93
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}
95
95
96
-
In JavaScript, these two code snippets are**not**equivalent:
96
+
En JavaScript, estos dos fragmentos de código**no**son equivalentes.
97
97
98
98
```js
99
99
obj.method();
@@ -104,50 +104,50 @@ var method = obj.method;
104
104
method();
105
105
```
106
106
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.
108
108
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.
110
112
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}
112
114
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:
116
116
117
117
```jsx
118
118
render() {
119
-
//Wrong: handleClick is called instead of passed as a reference!
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.
184
184
185
185
```jsx
186
-
constA=65// ASCII character code
186
+
constA=65//código ASCII del carácter
187
187
188
188
classAlphabetextendsReact.Component {
189
189
constructor(props) {
@@ -218,23 +218,23 @@ class Alphabet extends React.Component {
218
218
}
219
219
```
220
220
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}
222
222
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:
224
224
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))
228
228
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`.
230
230
231
-
> Note:
231
+
> Nota:
232
232
>
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.
234
234
235
235
#### Throttle {#throttle}
236
236
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.
238
238
239
239
```jsx
240
240
importthrottlefrom'lodash.throttle';
@@ -262,7 +262,7 @@ class LoadMoreButton extends React.Component {
262
262
263
263
#### Debounce {#debounce}
264
264
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.
266
266
267
267
```jsx
268
268
importdebouncefrom'lodash.debounce';
@@ -290,9 +290,9 @@ class Searchbox extends React.Component {
290
290
}
291
291
292
292
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
296
296
this.emitChangeDebounced(e.target.value);
297
297
}
298
298
@@ -304,11 +304,11 @@ class Searchbox extends React.Component {
[`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.
308
308
309
-
>**Note:**
309
+
>**Nota:**
310
310
>
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)
312
312
313
313
```jsx
314
314
importrafSchedulefrom'raf-schd';
@@ -319,20 +319,20 @@ class ScrollListener extends React.Component {
319
319
320
320
this.handleScroll=this.handleScroll.bind(this);
321
321
322
-
//Create a new function to schedule updates.
322
+
//Crea una nueva función para agendar actualizaciones
323
323
this.scheduleUpdate=rafSchedule(
324
324
point=>this.props.onScroll(point)
325
325
);
326
326
}
327
327
328
328
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
//Cancel any pending updates since we're unmounting.
335
+
//Cancela cualquier actualizacion pendiente ya que estamos 'unmounting'.
336
336
this.scheduleUpdate.cancel();
337
337
}
338
338
@@ -349,6 +349,6 @@ class ScrollListener extends React.Component {
349
349
}
350
350
```
351
351
352
-
#### Testing your rate limiting {#testing-your-rate-limiting}
352
+
#### Probando tu límite de cuadros {#testing-your-rate-limiting}
353
353
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