diff --git a/src/content/learn/responding-to-events.md b/src/content/learn/responding-to-events.md index 782b6c0f1..73eeaa76a 100644 --- a/src/content/learn/responding-to-events.md +++ b/src/content/learn/responding-to-events.md @@ -1,24 +1,24 @@ --- -title: Responding to Events +title: Обработка событий --- -React lets you add *event handlers* to your JSX. Event handlers are your own functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on. +React позволяет добавлять *обработчики событий* прямо в JSX. Обработчики событий - это функции, которые вызываются в ответ на определенное событие, например, клик на элемент, наведение курсора, фокус поля формы и т.д. -* Different ways to write an event handler -* How to pass event handling logic from a parent component -* How events propagate and how to stop them +* Различные способы написания обработчика событий +* Как передавать логику обработки событий от родительского компонента +* Как события распространяются и как их остановить -## Adding event handlers {/*adding-event-handlers*/} +## Добавление обработчиков событий {/*adding-event-handlers*/} -To add an event handler, you will first define a function and then [pass it as a prop](/learn/passing-props-to-a-component) to the appropriate JSX tag. For example, here is a button that doesn't do anything yet: +Чтобы добавить обработчик событий, сначала нужно определить функцию, а затем передать ее [в качестве пропа](/learn/passing-props-to-a-component) в соответствующий JSX-тег. Например, вот кнопка, у которой пока нет обработчика событий: @@ -26,7 +26,7 @@ To add an event handler, you will first define a function and then [pass it as a export default function Button() { return ( ); } @@ -34,23 +34,23 @@ export default function Button() { -You can make it show a message when a user clicks by following these three steps: +Для того, чтобы при нажатии на кнопку появилось сообщение, выполните эти шаги: -1. Declare a function called `handleClick` *inside* your `Button` component. -2. Implement the logic inside that function (use `alert` to show the message). -3. Add `onClick={handleClick}` to the ` ); } @@ -62,77 +62,77 @@ button { margin-right: 10px; } -You defined the `handleClick` function and then [passed it as a prop](/learn/passing-props-to-a-component) to ` ); } function UploadButton() { return ( - ); } @@ -207,7 +207,7 @@ function UploadButton() { export default function Toolbar() { return (
- +
); @@ -220,22 +220,24 @@ button { margin-right: 10px; } -Here, the `Toolbar` component renders a `PlayButton` and an `UploadButton`: +Здесь компонент `Toolbar` рендерит компоненты `PlayButton` и `UploadButton`: -- `PlayButton` passes `handlePlayClick` as the `onClick` prop to the `Button` inside. -- `UploadButton` passes `() => alert('Uploading!')` as the `onClick` prop to the `Button` inside. -Finally, your `Button` component accepts a prop called `onClick`. It passes that prop directly to the built-in browser ` - ); @@ -268,9 +270,9 @@ button { margin-right: 10px; } -In this example, ` ); @@ -312,13 +314,13 @@ button { margin-right: 10px; } -Notice how the `App` component does not need to know *what* `Toolbar` will do with `onPlayMovie` or `onUploadImage`. That's an implementation detail of the `Toolbar`. Here, `Toolbar` passes them down as `onClick` handlers to its `Button`s, but it could later also trigger them on a keyboard shortcut. Naming props after app-specific interactions like `onPlayMovie` gives you the flexibility to change how they're used later. +Заметьте, что компонент `App` не должен знать, *что* делает `Toolbar` с `onPlayMovie` или `onUploadImage`. Это детали реализации `Toolbar`. Здесь `Toolbar` передает их в качестве обработчиков `onClick` своим кнопкам, но позже он также может вызывать их по клавиатурному сочетанию. Называние пропсов в соответствии со спецификой вашего приложения, например `onPlayMovie`, дает вам гибкость в изменении их использовании в будущем. -## Event propagation {/*event-propagation*/} +## Всплытие событий {/*event-propagation*/} -Event handlers will also catch events from any children your component might have. We say that an event "bubbles" or "propagates" up the tree: it starts with where the event happened, and then goes up the tree. +Обработчики событий также будут перехватывать события от любых дочерних компонентов вашего компонента. Говорят, что событие "всплывает" или "распространяется" вверх по дереву: оно начинается там, где произошло событие, а затем поднимается вверх по дереву. -This `
` contains two buttons. Both the `
` *and* each button have their own `onClick` handlers. Which handlers do you think will fire when you click a button? +Этот `
` содержит две кнопки. У `
` *и* каждой кнопки есть свои собственные обработчики `onClick`. Какие обработчики вы думаете будут вызваны, когда вы нажмете на кнопку? @@ -326,13 +328,13 @@ This `
` contains two buttons. Both the `
` *and* each button have their export default function Toolbar() { return (
{ - alert('You clicked on the toolbar!'); + alert('Вы нажали на панель инструментов!'); }}> - -
); @@ -349,19 +351,19 @@ button { margin: 5px; } -If you click on either button, its `onClick` will run first, followed by the parent `
`'s `onClick`. So two messages will appear. If you click the toolbar itself, only the parent `
`'s `onClick` will run. +Если вы нажмете на любую кнопку, то сначала будет выполнен ее обработчик `onClick`, а затем обработчик `onClick` родительского элемента `
`. Таким образом, появится два сообщения. Если вы нажмете на саму панель инструментов, то будет выполнен только обработчик `onClick` родительского элемента `
`. -All events propagate in React except `onScroll`, which only works on the JSX tag you attach it to. +В React все события распространяются, за исключением `onScroll`, который работает только на теге JSX, к которому он привязан. -### Stopping propagation {/*stopping-propagation*/} +### Остановка распространения событий {/*stopping-propagation*/} -Event handlers receive an **event object** as their only argument. By convention, it's usually called `e`, which stands for "event". You can use this object to read information about the event. +Обработчики событий получают **объект события** в качестве единственного аргумента. Этот объект обычно называется `e`, что означает "event". С помощью этого объекта вы можете прочитать информацию о событии. -That event object also lets you stop the propagation. If you want to prevent an event from reaching parent components, you need to call `e.stopPropagation()` like this `Button` component does: +Объект события также позволяет остановить распространение события. Если вы хотите предотвратить достижение события родительским компонентам, вам необходимо вызвать метод `e.stopPropagation()`, как это делает компонент `Button`: @@ -382,11 +384,11 @@ export default function Toolbar() {
{ alert('You clicked on the toolbar!'); }}> - -
); @@ -403,43 +405,43 @@ button { margin: 5px; }
-When you click on a button: +При нажатии на кнопку: -1. React calls the `onClick` handler passed to `
``` -Each event propagates in three phases: +Каждое событие распространяется в трех фазах: -1. It travels down, calling all `onClickCapture` handlers. -2. It runs the clicked element's `onClick` handler. -3. It travels upwards, calling all `onClick` handlers. +1. Оно спускается вниз, вызывая все обработчики `onClickCapture`. +2. Оно вызывает обработчик `onClick` для нажатого элемента. +3. Оно поднимается вверх, вызывая все обработчики `onClick`. -Capture events are useful for code like routers or analytics, but you probably won't use them in app code. +События захвата полезны для кода, такого как роутеры или аналитика, но, вероятно, вы не будете использовать их в приложении. -### Passing handlers as alternative to propagation {/*passing-handlers-as-alternative-to-propagation*/} +### Передача обработчиков в качестве альтернативы распространению событий {/*passing-handlers-as-alternative-to-propagation*/} -Notice how this click handler runs a line of code _and then_ calls the `onClick` prop passed by the parent: +Обратите внимание, как этот обработчик клика выполняет строку кода, _а затем_ вызывает переданный родителем проп `onClick`: ```js {4,5} function Button({ onClick, children }) { @@ -454,22 +456,22 @@ function Button({ onClick, children }) { } ``` -You could add more code to this handler before calling the parent `onClick` event handler, too. This pattern provides an *alternative* to propagation. It lets the child component handle the event, while also letting the parent component specify some additional behavior. Unlike propagation, it's not automatic. But the benefit of this pattern is that you can clearly follow the whole chain of code that executes as a result of some event. +Вы также можете добавить больше кода в этот обработчик перед вызовом обработчика событий `onClick` родительского компонента. Этот шаблон обеспечивает *альтернативу* распространению. Он позволяет дочернему компоненту обрабатывать событие, а также позволяет родительскому компоненту указывать дополнительное поведение. В отличие от распространения, это не происходит автоматически. Но преимущество этого шаблона заключается в том, что вы можете четко следить за всей цепочкой кода, который выполняется в результате какого-либо события. -If you rely on propagation and it's difficult to trace which handlers execute and why, try this approach instead. +Если вы полагаетесь на распространение, и трудно отследить, какие обработчики выполняются и почему, попробуйте использовать этот подход. -### Preventing default behavior {/*preventing-default-behavior*/} +### Предотвращение стандартного поведения {/*preventing-default-behavior*/} -Some browser events have default behavior associated with them. For example, a `
` submit event, which happens when a button inside of it is clicked, will reload the whole page by default: +Некоторые события в браузере имеют связанное со стандартным поведением. Например, событие отправки формы ``, которое происходит при нажатии на кнопку внутри нее, по умолчанию перезагружает всю страницу: ```js export default function Signup() { return ( - alert('Submitting!')}> + alert('Отправление!')}> - + ); } @@ -481,7 +483,7 @@ button { margin-left: 5px; }
-You can call `e.preventDefault()` on the event object to stop this from happening: +Вы можете вызвать метод `e.preventDefault()` из объекта события, чтобы предотвратить это: @@ -490,10 +492,10 @@ export default function Signup() { return (
{ e.preventDefault(); - alert('Submitting!'); + alert('Отправление!'); }}> - +
); } @@ -505,28 +507,28 @@ button { margin-left: 5px; }
-Don't confuse `e.stopPropagation()` and `e.preventDefault()`. They are both useful, but are unrelated: +Не путайте `e.stopPropagation()` и `e.preventDefault()`. Оба они полезны, но не связаны между собой: -* [`e.stopPropagation()`](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) stops the event handlers attached to the tags above from firing. -* [`e.preventDefault()` ](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) prevents the default browser behavior for the few events that have it. +* [e.stopPropagation()](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) останавливает срабатывание обработчиков событий, привязанных к тегам выше по иерархии DOM. +* [e.preventDefault()](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) предотвращает стандартное поведение браузера для некоторых событий. -## Can event handlers have side effects? {/*can-event-handlers-have-side-effects*/} +## Могут ли обработчики событий иметь побочные эффекты? {/*can-event-handlers-have-side-effects*/} -Absolutely! Event handlers are the best place for side effects. +Конечно! Обработчики событий - это лучшее место для побочных эффектов. -Unlike rendering functions, event handlers don't need to be [pure](/learn/keeping-components-pure), so it's a great place to *change* something—for example, change an input's value in response to typing, or change a list in response to a button press. However, in order to change some information, you first need some way to store it. In React, this is done by using [state, a component's memory.](/learn/state-a-components-memory) You will learn all about it on the next page. +В отличие от функций рендеринга, обработчики событий не обязаны быть [чистыми функциями](/learn/keeping-components-pure), поэтому это отличное место для изменения чего-то - например, изменения значения ввода в ответ на набор текста или изменения списка при нажатии на кнопку. Однако, чтобы изменить какую-то информацию, сначала нужно иметь способ ее хранения. В React для этого используется [состояние компонента - его память](/learn/state-a-components-memory). Вы узнаете об этом на следующей странице. -* You can handle events by passing a function as a prop to an element like ` ); } @@ -563,7 +565,7 @@ export default function LightSwitch() { -The problem is that ` ); } @@ -588,7 +590,7 @@ export default function LightSwitch() { -Alternatively, you could wrap the call into another function, like ` ); } @@ -615,11 +617,11 @@ export default function LightSwitch() { -#### Wire up the events {/*wire-up-the-events*/} +#### Подключение обработчиков событий {/*wire-up-the-events*/} -This `ColorSwitch` component renders a button. It's supposed to change the page color. Wire it up to the `onChangeColor` event handler prop it receives from the parent so that clicking the button changes the color. +Этот компонент `ColorSwitch` отображает кнопку, которая должна изменять цвет страницы. Подключите её к обработчику событий `onChangeColor`, который он получает от родительского компонента, так что при нажатии на кнопку изменяется цвет страницы. -After you do this, notice that clicking the button also increments the page click counter. Your colleague who wrote the parent component insists that `onChangeColor` does not increment any counters. What else might be happening? Fix it so that clicking the button *only* changes the color, and does _not_ increment the counter. +После выполнения этой задачи вы заметите, что при нажатии на кнопку также увеличивается счетчик кликов на странице. Ваш коллега, который написал родительский компонент, настаивает на том, что `onChangeColor` не должен увеличивать никакие счетчики. Что еще может происходить? Исправьте это, чтобы при нажатии на кнопку _менялся_ только цвет, и _не_ увеличивался счетчик. @@ -629,7 +631,7 @@ export default function ColorSwitch({ }) { return ( ); } @@ -663,7 +665,7 @@ export default function App() {

-

Clicks on the page: {clicks}

+

Нажатий на страницу: {clicks}

); } @@ -673,9 +675,9 @@ export default function App() { -First, you need to add the event handler, like ` ); } @@ -722,7 +724,7 @@ export default function App() {

-

Clicks on the page: {clicks}

+

Нажатий на страницу: {clicks}

); }