-
Notifications
You must be signed in to change notification settings - Fork 391
Translate "Handling events" #89
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
Merged
another-guy
merged 7 commits into
reactjs:master
from
dpatrikeev:translation-basics-handling-events
Feb 21, 2019
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2856cdf
handling events translation
00e60cc
some minor changes
1dc4169
revise translation
dpatrikeev 707ebbe
fix after review feedback
cd144cb
fix after review feedback
ec1ebcd
fix after @another-guy review
dd48eb5
final touches
dpatrikeev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,72 +1,72 @@ | ||||||
--- | ||||||
id: handling-events | ||||||
title: Handling Events | ||||||
title: Обработка событий | ||||||
permalink: docs/handling-events.html | ||||||
prev: state-and-lifecycle.html | ||||||
next: conditional-rendering.html | ||||||
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: | ||||||
Обработка событий в React-элементах очень похожа на обработку событий в DOM-элементах. Но есть несколько синтаксических отличий: | ||||||
lex111 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
* React events are named using camelCase, rather than lowercase. | ||||||
* With JSX you pass a function as the event handler, rather than a string. | ||||||
* События в React именуются в стиле camelCase вместо нижнего регистра. | ||||||
* С JSX вы передаёте функцию как обработчик события вместо строки. | ||||||
|
||||||
For example, the HTML: | ||||||
Например, в HTML: | ||||||
|
||||||
```html | ||||||
<button onclick="activateLasers()"> | ||||||
Activate Lasers | ||||||
Активировать лазеры | ||||||
</button> | ||||||
``` | ||||||
|
||||||
is slightly different in React: | ||||||
В React немного иначе: | ||||||
|
||||||
```js{1} | ||||||
<button onClick={activateLasers}> | ||||||
Activate 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: | ||||||
Еще одно отличие — в React нельзя предотвратить обработчик события по умолчанию, вернув `false`. Нужно явно вызвать `preventDefault`. Например, в обычном HTML, чтобы отменить выполнение встроенного обработчика события у ссылки, которое открывает новую страницу, можно написать: | ||||||
|
||||||
```html | ||||||
<a href="#" onclick="console.log('The link was clicked.'); return false"> | ||||||
Click me | ||||||
<a href="#" onclick="console.log('По ссылке кликнули.'); return false"> | ||||||
Кликни меня | ||||||
</a> | ||||||
``` | ||||||
|
||||||
In React, this could instead be: | ||||||
В React это будет выглядеть так: | ||||||
|
||||||
```js{2-5,8} | ||||||
function ActionLink() { | ||||||
function handleClick(e) { | ||||||
e.preventDefault(); | ||||||
console.log('The link was clicked.'); | ||||||
console.log('По ссылке кликнули.'); | ||||||
} | ||||||
|
||||||
return ( | ||||||
<a href="#" onClick={handleClick}> | ||||||
Click me | ||||||
Кликни меня | ||||||
</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. | ||||||
Здесь `e` — это синтетическое событие. React определяет синтетические события в соответствии со [спецификацией W3C](https://www.w3.org/TR/DOM-Level-3-Events/), поэтому не волнуйтесь о кроссбраузерности. Посмотрите [руководство о `SyntheticEvent`](/docs/events.html), чтобы узнать о них больше. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А если конкретизируем, а то ещё короткое предложение получается?
Suggested change
|
||||||
|
||||||
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. | ||||||
При использовании React обычно не нужно вызывать `addEventListener`, чтобы добавить обработчики в DOM-элемент после его создания. Вместо этого добавьте обработчик сразу после того, как элемент отрендерился. | ||||||
|
||||||
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: | ||||||
В компоненте, определённом с помощью [ES6-класса](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Classes), в качестве обработчика события обычно выступает один из методов класса. Например, этот компонент `Toggle` рендерит кнопку, которая позволяет пользователю переключать состояния между «Включено» и «Выключено»: | ||||||
|
||||||
```js{6,7,10-14,18} | ||||||
class Toggle extends React.Component { | ||||||
constructor(props) { | ||||||
super(props); | ||||||
this.state = {isToggleOn: true}; | ||||||
|
||||||
// This binding is necessary to make `this` work in the callback | ||||||
// Эта привязка обязательна для работы `this` в колбэке. | ||||||
this.handleClick = this.handleClick.bind(this); | ||||||
} | ||||||
|
||||||
|
@@ -79,7 +79,7 @@ class Toggle extends React.Component { | |||||
render() { | ||||||
return ( | ||||||
<button onClick={this.handleClick}> | ||||||
{this.state.isToggleOn ? 'ON' : 'OFF'} | ||||||
{this.state.isToggleOn ? 'Включено' : 'Выключено'} | ||||||
</button> | ||||||
); | ||||||
} | ||||||
|
@@ -91,64 +91,64 @@ ReactDOM.render( | |||||
); | ||||||
``` | ||||||
|
||||||
[**Try it on CodePen**](http://codepen.io/gaearon/pen/xEmzGg?editors=0010) | ||||||
[**Посмотреть на 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. | ||||||
Будьте внимательны со значением `this` в JSX-колбэках. В JavaScript методы класса не [привязаны](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) по умолчанию. Если вы забудете привязать метод `this.handleClick` и передать его в `onClick`, `this` будет `undefined` в момент вызова функции. | ||||||
|
||||||
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. | ||||||
Дело не в работе React, это часть того, [как работают функции в JavaScript](https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/). Обычно, если ссылаться на метод без `()` после него, например, `onClick={this.handleClick}`, этот метод нужно привязать. | ||||||
|
||||||
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: | ||||||
Если вам не по душе `bind`, существует два других способа. Если вы пользуетесь экспериментальным [синтаксисом общедоступных полей классов](https://babeljs.io/docs/plugins/transform-class-properties/), вы можете использовать его, чтобы правильно привязать колбэки: | ||||||
|
||||||
```js{2-6} | ||||||
class LoggingButton extends React.Component { | ||||||
// This syntax ensures `this` is bound within handleClick. | ||||||
// Warning: this is *experimental* syntax. | ||||||
// Такой синтаксис гарантирует, что `this` привязан к handleClick. | ||||||
// Предупреждение: это экспериментальный синтаксис | ||||||
handleClick = () => { | ||||||
console.log('this is:', this); | ||||||
console.log('значение this:', this); | ||||||
} | ||||||
|
||||||
render() { | ||||||
return ( | ||||||
<button onClick={this.handleClick}> | ||||||
Click me | ||||||
Кликни по мне | ||||||
</button> | ||||||
); | ||||||
} | ||||||
} | ||||||
lex111 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
``` | ||||||
|
||||||
This syntax is enabled by default in [Create React App](https://github.com/facebookincubator/create-react-app). | ||||||
Такой синтаксис доступен в [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: | ||||||
Если вы не пользуетесь синтаксисом полей, можете попробовать [стрелочные функции](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions) в колбэке: | ||||||
|
||||||
```js{7-9} | ||||||
class LoggingButton extends React.Component { | ||||||
handleClick() { | ||||||
console.log('this is:', this); | ||||||
console.log('значение this:', this); | ||||||
} | ||||||
lex111 marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
render() { | ||||||
// This syntax ensures `this` is bound within handleClick | ||||||
// Такой синтаксис гарантирует, что `this` привязан к handleClick. | ||||||
return ( | ||||||
<button onClick={(e) => this.handleClick(e)}> | ||||||
Click me | ||||||
Кликни по мне | ||||||
</button> | ||||||
); | ||||||
} | ||||||
} | ||||||
``` | ||||||
|
||||||
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. | ||||||
Проблема этого синтаксиса в том, что при каждом рендере `LoggingButton` создается новый колбэк. Чаще всего это не страшно. Однако, если этот колбэк попадает как проп в дочерние компоненты, эти компоненты могут быть отрендерены снова. Мы рекомендуем делать привязку в конструкторе или использовать синтаксис полей классов, чтобы избежать проблем с производительностью. | ||||||
|
||||||
## Passing Arguments to Event Handlers {#passing-arguments-to-event-handlers} | ||||||
## Передача аргументов в обработчики событий {#passing-arguments-to-event-handlers} | ||||||
|
||||||
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: | ||||||
Внутри цикла часто нужно передать дополнительный аргумент в обработчик события. Например, если `id` — это идентификатор строки, можно использовать следующие варианты: | ||||||
|
||||||
```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)}>Удалить строку</button> | ||||||
<button onClick={this.deleteRow.bind(this, id)}>Удалить строку</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. | ||||||
Две строки выше — эквивалентны, и используют [стрелочные функции](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions) и [`Function.prototype.bind`](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) соответственно. | ||||||
|
||||||
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. | ||||||
В обоих случаях аргумент `e`, представляющий событие React, будет передан как второй аргумент после идентификатора. Используя стрелочную функцию, необходимо передавать аргумент явно, но с `bind` любые последующие аргументы передаются автоматически. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.