Event persist react что это
Реагировать на предотвращение всплытия событий во вложенных компонентах при нажатии
Я играл с e.preventDefault (), e.stopPropagation (), но безрезультатно.
8 ответов
Я была такая же проблема. Я обнаружил, что stopPropagation действительно работает. Я бы разделил элемент списка на отдельный компонент, вот так:
Пока вы не вызываете persist что-то, что могло бы создать значительную память для создания событий, таких как onMouseMove (и вы не создаете какую-то игру Cookie Clicker, такую как Cookies бабушки), это должно быть прекрасно!
Также обратите внимание: время от времени читая их GitHub, мы должны следить за будущими версиями React, поскольку они могут в конечном итоге решить некоторые проблемы, связанные с этим, поскольку они, похоже, собираются сделать складной код React в компиляторе / транспиляторе.
Это простой способ предотвратить переход события click к следующему компоненту, а затем вызвать ваш yourFunction.
По порядку событий DOM: ЗАХВАТ vs ЗАПУСК
Сначала происходит этап захвата, затем следует этап всплывания. Когда вы регистрируете событие с помощью обычного DOM api, события будут по умолчанию частью этапа восходящей цепочки, но это можно указать при создании события.
В React всплывающие события также используются по умолчанию.
Заглянем внутрь нашего обратного вызова handleClick (React):
Альтернатива, о которой я здесь не видел
Если вы вызываете e.preventDefault () во всех своих событиях, вы можете проверить, было ли событие уже обработано, и предотвратить его повторную обработку:
Информацию о разнице между синтетическими и собственными событиями см. В документации React: https://reactjs.org/docs/ events.html
Вы можете избежать всплытия событий, проверив цель события.
Например, если у вас есть ввод, вложенный в элемент div, где у вас есть обработчик для события щелчка, и вы не хотите его обрабатывать, при нажатии на ввод вы можете просто передать event.target в свой обработчик и проверить обработчик должен выполняться на основе свойств цели.
Например, вы можете проверить if (target.localName === «input») < return>.
Итак, это способ «избежать» выполнения обработчика
React использует делегирование событий с одним прослушивателем событий в документе для событий, которые всплывают, например «щелчок» в этом примере, что означает, что остановить распространение невозможно; реальное событие уже распространено к тому моменту, когда вы взаимодействуете с ним в React. stopPropagation в синтетическом событии React возможно, потому что React обрабатывает распространение синтетических событий внутри себя.
React SyntheticEvent reuse
How does React manage the event system?
For performance reasons, React reuses the SyntheticEvent objects by pooling them. This means that the SyntheticEvent object is reused, so after an event handler is invoked all the properties on event.target are nullified.
“Warning: This synthetic event is reused for performance reasons”
This warning is triggered when we try to access to a React synthetic event in an asynchronous way. Because of the reuse, after the event callback has been invoked the synthetic event object will no longer exist so we cannot access its properties.
Solution 1: event.persist()
Calling event.persist() on the synthetic event removes the event from the pool allowing references to the event to be retained asynchronously.
Solution 2: cache the needed properties
We can store the event properties in the event handler and pass them to the asynchronous callback instead of accessing the event directly from the asynchronous callback:
Debouncing a synthetic event handler.
Another common example apart from setState is a debounced callback:
The debounce method from lodash creates the function which will be invoked asynchronously so if we try to access the object directly from the debounced callback, the synthetic event will be already nullified.
The example below fixes the problem by caching the event properties. In this case, we access the event value out of the debounced code and pass it to the debounced callback.
Synthetic Events in React
A persistent problem
Jun 6, 2019 · 5 min read
What are synthetic events and why do we need them?
How do events work in React?
To handle even t s, a browser’s Javascript API generally has an Event class, and every native event that triggers creates an instance of this class that gets passed as an argument to a callback function.
React, however, pools SyntheticEvent objects between all events, meaning that there is only one active SyntheticEvent object at a time. When an event is triggered, the properties of the SyntheticEvent object are set using the browser native event. The SyntheticEvent object is then passed to your callback function. Once the callback function is complete, the SyntheticEvent object will be nullified (all its properties will be reset to null ) so that it can be reused by the next event handler.
We could try to delve into why React events work this way but, essentially, this was a decision made by the React team for performance reasons, so we just have to roll with it.
An interesting side note — as well as only having one SyntheticEvent object, React only has one event listener. React employs top-level event delegation. Rather than attach an event listener to each DOM node that we specify, React creates a single, top-level event listener that can capture all native browser events. When we mount and unmount a component in which we have specified some event handling, this is just added to the internal mapping of the top-level event listener.
How can synthetic events be a problem?
Since the SyntheticEvent object is nullified once the callback function has completed, it can not be accessed asynchronously.
Here is a simple demo app to demonstrate:
This app has 2 divs:
The first says ‘I want this text’ and has an on-click event that console logs the div’s text and stores the event itself in state.
The second says ‘I don’t want this text’ and has an on-click event that logs the text of the target element of the event stored in state.
With a bit of CSS, it looks like this:
I’m storing the event in state because I want to retrieve some of its properties later. My expectation is that clicking the second div should access the event stored in state and console log the inner text of its target element: ‘I want this text’.
But this won’t work. If we want to store our event, we need to be aware that objects in Javascript are passed by reference, so all we are storing is a reference to the SyntheticEvent object. This means that the properties of the SyntheticEvent will not remain fixed. The initial problem we will encounter is that the data we might want to retrieve from the SyntheticEvent object later has been nullified.
Here we can see that clicking the first div sets the SyntheticEvent object in state. When we try to access the SyntheticEvent object through the React Developer Tools, we are bombarded with warnings. That is a warning for each property of the SyntheticEvent object, telling us that it has been nullified. As we scroll through the object, we can also see that the value of every property (except for functions) is now null.
The worse problem comes when other events trigger. Remember, the SyntheticEvent object is reused for all events and we have only stored a reference to it in state. This means that, when another event fires (for the duration of its callback) the event in our state will actually have its properties set to new values we don’t want.
Here we can see that, instead of logging the text of the first div as we’d intended, we’re getting the text of the second div. When we click on the second div, this triggers a new event whose properties React assigns to the SyntheticEvent object (including, importantly for this example, the target element). The callback function of the second div’s on-click event then looks at the event stored in state to find the inner text of its target. That target is now the second div and so it ends up logging its own inner text, rather than the text of the first div as we’d intended.
So how can we avoid this problem?
1. Cache the event data — This is the most obvious way, and you’re almost certainly already doing this anyway. Rather than save the event in state, we can pull out the data we need during the callback function and set that in state. For the demo app, that would look something like this:
2. Persist the event — If you use event.persist() during your callback function, React will maintains the SyntheticEvent object with its current properties and remove it from the pool. Instead of nullifying and reusing this SyntheticEvent object, React will create a new one to be used by any later events. We can apply that to our earlier code like so:
And now, our app should work like we wanted:
Русские Блоги
Система событий React Event
Реагировать на события
React стандартизирует объект события, поэтому он будет иметь одинаковые свойства в разных браузерах.
Синтаксис привязки к событию: onClick =
Функция привязки событий
Касание происходит только на мобильных устройствах
onKeyPress да onKeyDown с onKeyUp Комбинация
В соответствии с копией, вырезать и вставить мы часто используем
onChange Может использоваться в полях ввода, переключателях, выпадающих списках, мы можем получать уведомления при каждом изменении содержимого onInput Использовать при вводе текста. onSubmit Он используется для ввода ввода всей формы и часто используется для запрета работы формы по умолчанию.
Класс элементов интерфейса
Событие onScroll будет запущено при запуске события прокрутки
События, вызываемые колесом мыши, амплитуда прокрутки монитора, ориентация прокрутки
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
демонстрация
Пул событий
Объекты виртуальных событий были объединены. Это означает, что объект виртуального события будет повторно использован, и все свойства будут недействительными после вызова обратного вызова события. Это из соображений производительности. Следовательно, вы не можете получить доступ к событиям асинхронным способом.
Объект события
Для v0.14 возврат false в обработчике событий не предотвратит всплытие события. Вместо этого в соответствующем сценарии приложения вызовите вручную e.stopPropagation() или e.preventDefault() 。
из их e Является ли объект события target Атрибут объекта события
(Следующее содержание в скобках)
Общие атрибуты
пузырьки (логическое) указывает, является ли событие пузырьковым
cancellable (логическое) указывает, можно ли отменить событие
currentTarget (DOMEventTarget) похож на Target, потому что событие может пузыриться, поэтому содержимое, выраженное двумя, отличается
defaultPrevented (логическое) указывает, запрещает ли событие поведение по умолчанию
eventPhase (число) указывает на стадию события
protectDefault () (void), соответствующий defaultPrevented, что означает, что поведение по умолчанию запрещено
stopPropagaTion () (void) соответствует пузырькам, что означает sh
timeStamp (число) timestamp, которое является событием, вызванным событием
тип (строка) Тип события
Уникальные свойства различных объектов событий
clipboardData (DOMDataTransfer) указывает полученные данные
altKey (логическое значение) указывает, следует ли нажимать клавишу Alt.
charCode (Number) представляет код символа клавиши, вы можете судить, какая клавиша нажата кодом
ctrlKey (булево) указывает, нужно ли нажимать клавишу ctrl
getModifierState (key) (function) указывает, нажата ли вспомогательная кнопка (вспомогательная кнопка является вспомогательной кнопкой, такой как NVC ctrl и shift), и может быть передана в коде клавиши, чтобы определить, нажата ли она
клавиша (строка) строка, нажатая клавиша
keyCode (Number) означает ключи, которые не являются символьными кодами
locale (String) указывает, что некоторые строки локализованы
местоположение (число) указывает местоположение
metaKey (логическое) представляет ключ выигрыша в системе win и соответствующий ключ команды в системе mac
repeat (булево) указывает, повторяется ли клавиша
shiftKey (логическое значение) указывает, нажата ли кнопка shift
which (Number) означает charCode и keyCode после обобщения
relatedTarget (DOMEventTarget) связанный объект фокуса
screenX (Number) Начало координат находится в верхнем левом углу дисплея
screenY (Number) Начало координат находится в верхнем левом углу дисплея
Чтобы событие касания вступило в силу, вызовите его перед рендерингом всех компонентов. React.initializeTouchEvents(true) 。
changeTouches (DOMTouchList) операция жеста судьи
targetTouches (DOMTouchList) определяет операцию жеста
штрихи (DOMTouchList) операция жеста судьи
События элемента интерфейса
деталь (номер) расстояние для прокрутки
интерфейс представления (DOMAbstractView), окно
deltaMode (Number) можно понимать как единицу движения
deltaX (число) фиксированное значение относительного расстояния перемещения оси X
deltaY (Number) Фиксированное расстояние перемещения оси Y
deltaZ (Number) Фиксированное значение относительного расстояния перемещения оси Z
Примеры
Прокрутка объекта события
События и состояния
Состояние не только реализует четкое соответствие внутренних результатов компонента, но также реализует взаимодействие между компонентом и пользователем, так что поведение пользователя и компонента тесно сочетается
this.setState устанавливает состояние
Примеры
Оригинальное объяснение React
SyntheticEvent
This reference guide documents the SyntheticEvent wrapper that forms part of React’s Event System. See the Handling Events guide to learn more.
Overview
If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it. Every SyntheticEvent object has the following attributes:
As of v0.14, returning false from an event handler will no longer stop event propagation. Instead, e.stopPropagation() or e.preventDefault() should be triggered manually, as appropriate.
Event Pooling
The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.
If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
Supported Events
React normalizes events so that they have consistent properties across different browsers.
Handling Events
Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:
For example, the HTML:
is slightly different in React:
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 form behavior of submitting, you can write:
In React, this could instead be:
Here, e is a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility. React events do not work exactly the same as native events. See the SyntheticEvent reference guide to learn more.
When using React, you generally don’t 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.
When you define a component using an ES6 class, 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:
This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick=
If calling bind annoys you, there are two ways you can get around this. If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks:
This syntax is enabled by default in Create React App.
If you aren’t using class fields syntax, you can use an arrow function in the callback:
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.
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:
The above two lines are equivalent, and use arrow functions and Function.prototype.bind respectively.
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.