diff --git a/src/content/learn/responding-to-events.md b/src/content/learn/responding-to-events.md index 4450c461..65281a01 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,76 @@ 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 +206,7 @@ function UploadButton() { export default function Toolbar() { return (
- +
); @@ -220,22 +219,22 @@ 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. +- `PlayButton` перадае `handlePlayClick` у якасці пропса `onClick` у кампанент `Button`. +- `UploadButton` перадае `() => alert('Запампоўваецца!')` у якасці пропса `onClick` у кампанент `Button`. -Finally, your `Button` component accepts a prop called `onClick`. It passes that prop directly to the built-in browser ` - ); @@ -268,9 +267,9 @@ button { margin-right: 10px; } -In this example, ` ); @@ -312,19 +311,19 @@ 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` сваім кампанентам `Button`, але пазней ён таксама можа выклікаць іх па спалучэнні клавіш. Называнне пропсаў у адпаведнасці са спецыфікай вашай праграмы, напрыклад `onPlayMovie`, дае вам магчымасць змяніць спосаб іх выкарыстання ў будучыні. -Make sure that you use the appropriate HTML tags for your event handlers. For example, to handle clicks, use [` - ); @@ -355,19 +354,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`: @@ -386,13 +385,13 @@ function Button({ onClick, children }) { export default function Toolbar() { return (
{ - alert('You clicked on the toolbar!'); + alert('Вы націснулі на панэль інструментаў!'); }}> - -
); @@ -409,43 +408,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 }) { @@ -460,22 +459,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('Адпраўка!')}> - + ); } @@ -487,7 +486,7 @@ button { margin-left: 5px; }
-You can call `e.preventDefault()` on the event object to stop this from happening: +Вы можаце выклікаць `e.preventDefault()` для аб'екта падзеі, каб прадухіліць гэта: @@ -496,10 +495,10 @@ export default function Signup() { return (
{ e.preventDefault(); - alert('Submitting!'); + alert('Адпраўка!'); }}> - +
); } @@ -511,28 +510,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 ` ); } @@ -569,7 +568,7 @@ export default function LightSwitch() { -The problem is that ` ); } @@ -594,7 +593,7 @@ export default function LightSwitch() { -Alternatively, you could wrap the call into another function, like ` ); } @@ -621,11 +620,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` не павялічвае ніякіх лічыльнікаў. Што яшчэ можа адбывацца? Выправіце гэта так, каб націсканне на кнопку *толькі* змяняла колер, а _не_ павялічвала лічыльнік. @@ -635,7 +634,7 @@ export default function ColorSwitch({ }) { return ( ); } @@ -669,7 +668,7 @@ export default function App() {

-

Clicks on the page: {clicks}

+

Колькасць націсканняў: {clicks}

); } @@ -679,9 +678,9 @@ export default function App() { -First, you need to add the event handler, like ` ); } @@ -728,7 +727,7 @@ export default function App() {

-

Clicks on the page: {clicks}

+

Колькасць націсканняў: {clicks}

); } diff --git a/src/sidebarLearn.json b/src/sidebarLearn.json index 135d86c5..dc17c2af 100644 --- a/src/sidebarLearn.json +++ b/src/sidebarLearn.json @@ -95,7 +95,7 @@ "tags": [], "routes": [ { - "title": "Responding to Events", + "title": "Рэагаванне на падзеі", "path": "/learn/responding-to-events" }, {