diff --git a/content/docs/handling-events.md b/content/docs/handling-events.md index a8d3a1f51..5c62ced75 100644 --- a/content/docs/handling-events.md +++ b/content/docs/handling-events.md @@ -1,6 +1,6 @@ --- id: handling-events -title: Handling Events +title: Manipulando eventos permalink: docs/handling-events.html prev: state-and-lifecycle.html next: conditional-rendering.html @@ -8,65 +8,65 @@ 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: +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 ``` -is slightly different in React: +É ligeiramente diferente com React: ```js{1} ``` -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 - - Click me + + Clique Aqui ``` -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 ( - Click me + Clique Aqui ); } ``` -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 + // Aqui utilizamos o `bind` para que o `this` funcione dentro da nossa callback this.handleClick = this.handleClick.bind(this); } @@ -91,18 +91,18 @@ 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. + // Atenção: essa é uma sintaxe *experimental*. handleClick = () => { console.log('this is:', this); } @@ -110,16 +110,16 @@ class LoggingButton extends React.Component { render() { return ( ); } } ``` -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 { @@ -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 ( - + + ``` -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.