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

Translation of the "Handling Events" page #3

Merged
merged 14 commits into from
Feb 8, 2019
Merged
Changes from 13 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
72 changes: 36 additions & 36 deletions content/docs/handling-events.md
Original file line number Diff line number Diff line change
@@ -1,72 +1,72 @@
---
id: handling-events
title: Handling Events
title: Manipulando eventos
permalink: docs/handling-events.html
prev: state-and-lifecycle.html
next: conditional-rendering.html
redirect_from:
- "docs/events-ko-KR.html"
cezaraugusto marked this conversation as resolved.
Show resolved Hide resolved
---

Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
Manipular eventos em elementos React é muito semelhante a manipular eventos em elementos do DOM. Existem algumas diferenças sintáticas:

* React events are named using camelCase, rather than lowercase.
* With JSX you pass a function as the event handler, rather than a string.
* Eventos em React são nomeados usando camelCase ao invés de letras minúsculas.
* Com o JSX você passa uma função como manipulador de eventos ao invés de um texto.

For example, the HTML:
Por exemplo, com HTML:

```html
<button onclick="activateLasers()">
Activate Lasers
Ativar lasers
</button>
```

is slightly different in React:
É ligeiramente diferente com React:

```js{1}
<button onClick={activateLasers}>
Activate Lasers
Ativar 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:
Outra diferença é que você não pode retornar `false` para evitar o comportamento padrão no React. Você deve chamar `preventDefault` explícitamente. Por exemplo, com HTML simples, para evitar que um link abra uma nova página, você pode escrever:

```html
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
<a href="#" onclick="console.log('O link foi clicado.'); return false">
Clique Aqui
</a>
```

In React, this could instead be:
No React, isso poderia ser:

```js{2-5,8}
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
console.log('O link foi clicado.');
}

return (
<a href="#" onClick={handleClick}>
Click me
Clique Aqui
</a>
);
}
```

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.
Aqui, "`e`" é um synthetic event. O React define esses eventos sintéticos de acordo com a [especificação W3C](https://www.w3.org/TR/DOM-Level-3-Events/). Então, não precisamos nos preocupar com a compatibilidade entre navegadores. Veja a página [`SyntheticEvent`](/docs/events.html) para saber mais.

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.
Ao usar o React você geralmente não precisa chamar `addEventListener` para adicionar ouvintes a um elemento no DOM depois que ele é criado. Ao invés disso você pode apenas definir um ouvinte quando o elemento é inicialmente renderizado.

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:
Quando você define um componente usando uma [classe do ES6](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Classes), um padrão comum é que um manipulador de eventos seja um método na classe. Por exemplo, este componente `Toggle` renderiza um botão que permite ao usuário alternar entre os estados "ON" e "OFF":

```js{6,7,10-14,18}
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.state = { isToggleOn: true };

// This binding is necessary to make `this` work in the callback
// Esse bind é necessário para fazer o `this` funcionar dentro do callback
this.handleClick = this.handleClick.bind(this);
}

Expand All @@ -91,35 +91,35 @@ ReactDOM.render(
);
```

[**Try it on CodePen**](http://codepen.io/gaearon/pen/xEmzGg?editors=0010)
[**Experimente no 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.
Você precisa ter cuidado com o significado do `this` nos callbacks do JSX. Em JavaScript, os métodos de classe não são [vinculados](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_objects/Function/bind) por padrão. Se você esquecer de fazer o bind de `this.handleClick` e passá-lo para um `onClick`, o `this` será `undefined` quando a função for realmente chamada.

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.
Este não é um comportamento específico do React. É uma parte de [como funcionam as funções em JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Geralmente, se você referir a um método sem `()` depois dele, como `onClick={this.handleClick}`, você deve fazer o bind manual deste método.

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:
Se ficar chamando "bind" incomoda você, há duas maneiras de contornar isso. Se você estiver usando a [sintaxe experimental de campos de classe pública](https://babeljs.io/docs/plugins/transform-class-properties/), você pode usar campos de classe para vincular callbaks corretamente:

```js{2-6}
class LoggingButton extends React.Component {
// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
// Essa sintaxe garante que o `this` seja vinculado ao handleClick.
iagobruno marked this conversation as resolved.
Show resolved Hide resolved
// Atenção: essa é uma sintaxe *experimental*.
handleClick = () => {
console.log('this is:', this);
}

render() {
return (
<button onClick={this.handleClick}>
Click me
Clique Aqui
</button>
);
}
}
```

This syntax is enabled by default in [Create React App](https://github.com/facebookincubator/create-react-app).
Essa sintaxe é habilitada por padrão no [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:
Se você não estiver usando a sintaxe de campos de classe, poderá usar uma [arrow function](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/Arrow_functions) como callback:

```js{7-9}
class LoggingButton extends React.Component {
Expand All @@ -128,7 +128,7 @@ class LoggingButton extends React.Component {
}

render() {
// This syntax ensures `this` is bound within handleClick
// Essa sintaxe garante que o `this` seja vinculado ao handleClick.
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
Expand All @@ -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.
O problema com esta sintaxe é que um callback diferente é criado toda vez que o `LoggingButton` é renderizado. Na maioria dos casos, tudo bem. No entanto, se esse callback for passado para componentes inferiores através de props, esses componentes poderão fazer uma renderização extra. Geralmente recomendamos a vinculação no construtor ou a sintaxe dos campos de classe para evitar esse tipo de problema de desempenho.

## Passing Arguments to Event Handlers {#passing-arguments-to-event-handlers}
## Passando Argumentos para Manipuladores de Eventos {#passando-argumentos-para-manipuladores-de-eventos}

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 uma estrutura de repetição é comum querer passar um parâmetro extra para um manipulador de evento. Por exemplo, se `id` é o ID de identificação da linha, qualquer um dos dois a seguir funcionará:

```js
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
<button onClick={(e) => this.deleteRow(id, e)}>Deletar linha</button>
<button onClick={this.deleteRow.bind(this, id)}>Deletar linha</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.
As duas linhas acima são equivalentes e usam [arrow functions](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/Arrow_functions) e [`Function.prototype.bind`](https://developer.mozilla.org/pt-BR/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.
Em ambos os casos, o argumento `e` representando o evento do React será passado como segundo argumento após o ID. Com uma arrow function, nós temos que passá-lo explicitamente. Mas com o `bind` outros argumentos adicionais serão automaticamente encaminhados.