Skip to content
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 Passing Functions to Components #16

Merged
merged 2 commits into from
Feb 17, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 70 additions & 69 deletions content/docs/faq-functions.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
---
id: faq-functions
title: Passing Functions to Components
title: Passando Funções para Componentes
permalink: docs/faq-functions.html
layout: docs
category: FAQ
---

### How do I pass an event handler (like onClick) to a component? {#how-do-i-pass-an-event-handler-like-onclick-to-a-component}
### Como eu passo um manipulador de eventos (como onClick) para um componente? {#how-do-i-pass-an-event-handler-like-onclick-to-a-component}

Pass event handlers and other functions as props to child components:
Passando manipuladores de evento e outras funções como props para componentes filhos:

```jsx
<button onClick={this.handleClick}>
```

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).
Se você precisa ter acesso ao componente pai no manipulador, você também precisa dar bind em uma função na instância do componente (veja abaixo)

### How do I bind a function to a component instance? {#how-do-i-bind-a-function-to-a-component-instance}
### Como eu dou bind em uma função na instância de um componente? {#how-do-i-bind-a-function-to-a-component-instance}

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.
Dependendo da sintaxe e etapas de build que você está usando, existem diversas maneiras de ter certeza que as funções tem acesso aos atributos dos componentes como `this.props` e `this.state`.

#### Bind in Constructor (ES2015) {#bind-in-constructor-es2015}
#### Bind no Constructor (ES2015) {#bind-in-constructor-es2015}

```jsx
class Foo extends Component {
Expand All @@ -29,71 +29,71 @@ class Foo extends Component {
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
console.log('Clicado');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
return <button onClick={this.handleClick}>Clique em mim!</button>;
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
}
}
```

#### Class Properties (Stage 3 Proposal) {#class-properties-stage-3-proposal}
#### Propriedades de Classe (Stage 3 Proposal) {#class-properties-stage-3-proposal}

```jsx
class Foo extends Component {
// Note: this syntax is experimental and not standardized yet.
// Nota: esta sintaxe é experimental e ainda não padronizada.
handleClick = () => {
console.log('Click happened');
console.log('Clicado');
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
return <button onClick={this.handleClick}>Clique em mim!</button>;
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
}
}
```

#### Bind in Render {#bind-in-render}
#### Bind no Render {#bind-in-render}

```jsx
class Foo extends Component {
handleClick() {
console.log('Click happened');
console.log('Clicado');
}
render() {
return <button onClick={this.handleClick.bind(this)}>Click Me</button>;
return <button onClick={this.handleClick.bind(this)}>Clique em mim!</button>;
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
}
}
```

>**Note:**
>**Nota:**
>
>Using `Function.prototype.bind` in render creates a new function each time the component renders, which may have performance implications (see below).
>Ao usar `Function.prototype.bind` no render, uma nova função é criada cada vez que o componente é renderizado, o que pode afetar a performance (veja abaixo).

#### Arrow Function in Render {#arrow-function-in-render}
#### Arrow Function no Render {#arrow-function-in-render}

```jsx
class Foo extends Component {
handleClick() {
console.log('Click happened');
console.log('Clicado');
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
return <button onClick={() => this.handleClick()}>Clique em mim!</button>;
glaucia86 marked this conversation as resolved.
Show resolved Hide resolved
}
}
```

>**Note:**
>**Nota:**
>
>Using an arrow function in render creates a new function each time the component renders, which may have performance implications (see below).
>Ao usar uma arrow function no render, uma nova função é criada cada vez que o componente é renderizado, o que pode afetar a performance (veja abaixo).

### Is it OK to use arrow functions in render methods? {#is-it-ok-to-use-arrow-functions-in-render-methods}
### Devemos usar arrow functions em métodos de render? {#is-it-ok-to-use-arrow-functions-in-render-methods}

Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.
De um modo geral, sim, é certo. E muitas das vezes é a maneira mais fácil de enviar parâmetros para funções de callback.

If you do have performance issues, by all means, optimize!
Se você tiver problemas de performance, de qualquer jeito, otimize!

### Why is binding necessary at all? {#why-is-binding-necessary-at-all}
### Porque binding é necessário afinal? {#why-is-binding-necessary-at-all}

In JavaScript, these two code snippets are **not** equivalent:
Em JavaScript, estes dois code snippets **não** são equivalentes:

```js
obj.method();
Expand All @@ -104,50 +104,50 @@ var method = obj.method;
method();
```

Binding methods helps ensure that the second snippet works the same way as the first one.
Métodos de binding ajudam a garantir que o segundo snippet funcione da mesma maneira que o primeiro.

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.
Com React, tipicamente você precisa dar bind apenas nos métodos que você *passa* para outros componentes. Por exemplo, `<button onClick={this.handleClick}>` passa `this.handleCLick` logo voce deve dar bind nele. Entretanto, é desnecessário usar bind no método `render` ou nos métodos do ciclo de vida: nós não passamos ele à outros componentes.

[Este post por Yehuda Katz](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/) explica o que binding é e como funcionam as funções do Javascript, em detalhes.

[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.
### Porque minha função é chamada toda vez que o componente renderiza? {#why-is-my-function-being-called-every-time-the-component-renders}

### Why is my function being called every time the component renders? {#why-is-my-function-being-called-every-time-the-component-renders}

Make sure you aren't _calling the function_ when you pass it to the component:
Certifique-se que você não está _chamando a função_ quando for passar para o componente:

```jsx
render() {
// Wrong: handleClick is called instead of passed as a reference!
return <button onClick={this.handleClick()}>Click Me</button>
// Errado: handleClick é chamado ao invés de ser passado como referência!
return <button onClick={this.handleClick()}>Clique em mim!</button>
}
```

Instead, *pass the function itself* (without parens):
Em vez disso, *passe a própria função* (sem parenteses):

```jsx
render() {
// Correct: handleClick is passed as a reference!
return <button onClick={this.handleClick}>Click Me</button>
// Correto: handleClick é passado como referência!
return <button onClick={this.handleClick}>Click em mim!</button>
}
```

### How do I pass a parameter to an event handler or callback? {#how-do-i-pass-a-parameter-to-an-event-handler-or-callback}
### Como eu passo um parâmetro para um manipulador de evento ou um callback? {#how-do-i-pass-a-parameter-to-an-event-handler-or-callback}

You can use an arrow function to wrap around an event handler and pass parameters:
Você pode usar uma arrow function para envolver um manipulador de eventos e passar parâmetros:

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

This is equivalent to calling `.bind`:
Isto é equivalente que chamar o `.bind`:

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

#### Example: Passing params using arrow functions {#example-passing-params-using-arrow-functions}
#### Exemplo: Passando parametros usando arrow functions {#exemplo-passando-parametros-usando-arrow-functions}

```jsx
const A = 65 // ASCII character code
const A = 65 // cógido de caractere ASCII

class Alphabet extends React.Component {
constructor(props) {
Expand Down Expand Up @@ -178,12 +178,12 @@ class Alphabet extends React.Component {
}
```

#### Example: Passing params using data-attributes {#example-passing-params-using-data-attributes}
#### Exemplo: Passando parâmetros usando data-attributes {#example-passing-params-using-data-attributes}

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.
Em vez disso, você pode usar APIs do DOM para armazenar dados necessários pra manipuladores de evento. Considere este approach caso você precise otimizar um grande número de elementos ou possua uma render tree que depende de verificações de igualdade do React.PureComponent.

```jsx
const A = 65 // ASCII character code
const A = 65 // código de caractere ASCII

class Alphabet extends React.Component {
constructor(props) {
Expand Down Expand Up @@ -218,23 +218,24 @@ class Alphabet extends React.Component {
}
```

### 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}
### Como eu posso evitar que uma função seja chamada muito rapidamente ou chamada muitas vezes em seguida? {#how-can-i-prevent-a-function-from-being-called-too-quickly-or-too-many-times-in-a-row}

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:
Se você tem um manipulador de eventos como `onClick` ou `onScroll` e quer evitar que o callback seja ativado muito rapidamente, então você pode limitar a taxa em que o callback é executado.
Isso pode ser feito usando:

- **throttling**: sample changes based on a time based frequency (eg [`_.throttle`](https://lodash.com/docs#throttle))
- **debouncing**: publish changes after a period of inactivity (eg [`_.debounce`](https://lodash.com/docs#debounce))
- **`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))
- **throttling**: amostra de mudanças com base em uma frequência baseada no tempo (eg [`_.throttle`](https://lodash.com/docs#throttle))
- **debouncing**: publica alterações após um período de inatividade (eg [`_.debounce`](https://lodash.com/docs#debounce))
- **`requestAnimationFrame` throttling**: amostra de mudanças baseadas em [`requestAnimationFrame`](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/requestAnimationFrame) (eg [`raf-schd`](https://github.com/alexreardon/raf-schd))

See [this visualization](http://demo.nimius.net/debounce_throttle/) for a comparison of `throttle` and `debounce` functions.
Veja [esta visualização](http://demo.nimius.net/debounce_throttle/) para uma comparação entre as funções `throttle` e `debounce`.

> Note:
> Nota:
>
> `_.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.
> `_.debounce`, `_.throttle` e `raf-schd` fornecem um método `cancel` para cancelar callbacks atrasados. Você deve chamar este método a partir de `componentWillUnmount` _ou_ verificar se o componente ainda está montado dentro da função atrasada.

#### Throttle {#throttle}

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.
O _throttling_ impede a função de ser chamada mais de uma vez em uma certa janela de tempo. O exemplo abaixo _throttles_ o manipulador do evento "Click" para impedi-lo de ser chamado mais de uma vez por segundo.

```jsx
import throttle from 'lodash.throttle';
Expand Down Expand Up @@ -262,7 +263,7 @@ class LoadMoreButton extends React.Component {

#### Debounce {#debounce}

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.
O _Debouncing_ garante que a função não vai ser executada até que uma certa quantidade de tempo tenha passado desde sua última chamada. Isso pode ser útil quando você tem que executar algum cálculo pesado em resposta a um evento que pode despachar rapidamente (eg rolagem ou evento de teclas). O exemplo abaixo _debounces_ o texto com um atraso de 250ms.

```jsx
import debounce from 'lodash.debounce';
Expand Down Expand Up @@ -290,9 +291,9 @@ class Searchbox extends React.Component {
}

handleChange(e) {
// React pools events, so we read the value before debounce.
// Alternately we could call `event.persist()` and pass the entire event.
// For more info see reactjs.org/docs/events.html#event-pooling
// o React faz pools no eventos. Então lemos o valor antes do debounce.
// Alternativamente podemos chamar `event.persist()` e passar todo o evento.
Para mais informações veja: reactjs.org/docs/events.html#event-pooling
this.emitChangeDebounced(e.target.value);
}

Expand All @@ -304,11 +305,11 @@ class Searchbox extends React.Component {

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

[`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.
[`requestAnimationFrame`](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/requestAnimationFrame) é uma maneira de enfileirar uma função para ser executada no browser no tempo ideal para a performance de renderização. A função que é enfileirada com `requestAnimationFrame` vai disparar no próximo frame. O browser trabalhará duro para garantir que haja 60 frames por segundo(60 fps). Entretanto, se o browser for incapaz disso, ele vai naturalmente *limitar* a quantidade de frames por segundo. Por exemplo, um dispostivo pode ser capaz de aguentar apenas 30fps e então você só tera 30 frames por segundo. Usar `requestAnimationFrame` para _throttling_ é uma técnica útil para prevenir você de fazer mais de 60 atualizações em um segundo. Se você está fazendo 100 atualizações em um segundo, isso cria trabalho adicional para o browser que de qualquer maneira o usuário não será capaz de ver.

>**Note:**
>**Nota:**
>
>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)
>Usar esta técnica capturará apenas o último valor publicado em um frame. Você pode ver um exemplo de como esta otimização funciona em [`MDN`](https://developer.mozilla.org/pt-BR/docs/Web/Events/scroll)

```jsx
import rafSchedule from 'raf-schd';
Expand All @@ -319,20 +320,20 @@ class ScrollListener extends React.Component {

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

// Create a new function to schedule updates.
// Cria uma nova função para agendar atualizações.
this.scheduleUpdate = rafSchedule(
point => this.props.onScroll(point)
);
}

handleScroll(e) {
// When we receive a scroll event, schedule an update.
// If we receive many updates within a frame, we'll only publish the latest value.
// Quando recebemos um evento de scroll, agenda-se uma atualização.
// Se recebermos muitos updates em um frames, publicaremos apenas o último valor.
this.scheduleUpdate({ x: e.clientX, y: e.clientY });
}

componentWillUnmount() {
// Cancel any pending updates since we're unmounting.
// Cancela qualquer atualização pendente já que estamos desmontando o componente.
this.scheduleUpdate.cancel();
}

Expand All @@ -349,6 +350,6 @@ class ScrollListener extends React.Component {
}
```

#### Testing your rate limiting {#testing-your-rate-limiting}
#### Testando sua taxa limitante {#testing-your-rate-limiting}

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.
Ao testar que o seu código de limitação de taxa funciona corretamente é útil ter a capacidade de avançar o tempo. Se você esta usando [`jest`](https://facebook.github.io/jest/) então você pdoe usar [`mock timers`](https://facebook.github.io/jest/docs/en/timer-mocks.html) para avançar o tempo. Se você está usando `requestAnimationFrame` _throttling_ você pode achar [`raf-stub`](https://github.com/alexreardon/raf-stub) uma ferramenta útil para controlar o instate dos quadros das animações.