onblur react что это
How onBlur and onChange events work in React
Table of Contents
In JavaScript, you might have come across onchange and onblur events. In React, they behave slightly differently. In this article, we will see what is the difference and how to use onChange and onBlur events in React for text inputs.
onchange and onblur events in JavaScript
Consider the following example in JavaScript:
We have a text input, and 2 events (onchange and onblur) bound to it. If you run the example in the Code Sandbox and open the console, you will see that:
onchange and onblur events in React
Here, we have converted the above JavaScript example to React:
If you open the browser console and test the below input, you will see that onChange event will be triggered on every keypress.
If you are browsing through mobile (or too lazy to open the browser console 😜), this is how the logs will look:
So the main difference between onChange event in JavaScript and React is that in JavaScript it will be triggered only when the user focuses out (after changing the text). However, in React onChange event will be triggered as soon as the user changes the text without waiting for the user to focus out.
Another obvious difference is that onChange in React is camel-cased. If you use all small cases, then you would get the following warning in the browser console and the functionality wouldn’t work:
Invalid event handler property `onchange`. Did you mean `onChange`?
Combining onBlur and onChange to validate the input
In one of my previous articles, I have written about form validation in React in depth. Here we will be focusing on just the email field validation using onBlur and onChange events.
Consider the following code:
Here as soon as the user starts typing, we are checking if the input is valid or not and showing the error message. You can check yourself in the below input:
This might not be a great user experience, since the user would want them to finish typing before they are told they have inputted incorrect data. This is when onBlur event comes handy. See the updated code below:
You can verify in the below input that the error message is displayed only after you focus out the text box.
That’s it in this article. If you have any queries, ask them in the comments below!
Do follow me on twitter where I post developer insights more often!
Событие React и blur
у меня есть простая проблема с React и обработкой событий. Мой компонент выглядит так (в основном таблицы):
Я хочу blur событие только если фокус выходит из таблицы. Вместо событие срабатывает на каждом дочернем элементе таблицы, когда он теряет фокус.
В соответствии с docs React позволяет фокусировать события пузырь вверх.
вопрос в том, как я могу получить свой onBlur способ огонь только тогда, когда фокус выходит из-за стола? IOW: как я могу отфильтровать и отбросить нежелательные события, пузырящиеся так, что я показываю только события, которые указывают на потерю фокуса для таблицы?
2 ответов
проблема в том, что таблица на самом деле не имеет концепции фокуса, поскольку это не сам вход.
когда onBlur срабатывает на содержащихся входах, мы проверим relatedTarget на onBlur событие, которое должно быть установлено на элемент, получивший фокус (или null ). Затем мы используем функцию, которая будет проходить вверх через parentNode s от этого недавно сфокусированного элемента и убедитесь, что наше событие currentTarget (таблица) не является предком вновь сфокусированного элемента. Если условие проходит предполагается, что таблица больше не имеет фокусировать.
обновление:
удалено использование ReactDOM.findDOMNode
без пользовательские функции и совместимость с Internet Explorer С node.contains и document.activeElement поддерживаются начиная с Internet Explorer 5, это работает:
onBlur для элемента div в React
Я хочу выполнить функцию после того, как элемент div покинул фокус.
Я использую функции tabIndex и onBlur внутри div. И он прекрасно работает, когда я вручную ставлю фокус, нажав на любой из элементов внутри div. Но по умолчанию, когда ни один элемент не нажат внутри div, он не работает.
Мой компонент-это функциональный компонент & div визуализируется динамически, поэтому я также не могу установить фокус с помощью useRef.
Код после того, как я нажму на значок, чтобы показать DIV
Код после onBlur вызывается
Так как же мне заставить onBlur работать с элементом div?
Следующее изображение показывает текущую направленность
1 ответ
У меня есть div в таблице
blur событие может быть очень хитрым, особенно если у вас есть фокусируемые элементы внутри фокусируемого элемента. Откройте консоль и немного поиграйте с этим фрагментом кода, чтобы лучше понять, как работают события ‘blur’ и ‘focus’.
blur event won’t happen if you click inside focused element. Exception if you have another focusable element inside and you click on it. But Notice that after main blur you will see input focus and main focus and if you will click outside of the main element you will also see two blur events: input blur and after that main blur
Похожие вопросы:
Я пишу компонент React (v0.14.7+), который должен вызвать обратный вызов onBlur (переданный через props), когда курсор покидает компонент (через tab, щелчок мыши или сенсорное событие). Проблема.
Как и выше, у меня есть кнопка, при нажатии на которую открывается подменю. Для каждого варианта в подменю есть три элемента (на самом деле их больше, я думаю, но для простоты сохраню их как 3). Я.
У меня есть два элемента: и динамически создаваемый (все это часть программы.
У меня есть div в таблице
Я подключаюсь к довольно большому проекту React JS, который использует react-data-grid для отображения кучи редактируемых данных. Прямо сейчас вам нужно нажать кнопку обновления, чтобы отправить.
Я реализую автозаполнение/combobox в dart. Для этого я использую два элемента: a и a
- для предложений. Я хочу скрыть через css стиль display: none всякий раз, когда.
Мое приложение react выводит текстовый ввод, который имеет функции для обработки как onKeyDown (использует условное выражение, чтобы проверить, является ли ключ ‘Enter’ или ‘Backspace’), так и.
В моем приложении React Native у меня есть a, к которому я хочу добавить стиль, когда он сфокусирован (измените textAlign с ‘center’ на ‘left’). Он отлично работает в iOS, но кажется, что на Android.
Как я могу извлечь innerHTML из события onBlur? Ранее я использовал только обработчики событий onChange и onClick. В этих случаях аргумент события (или, по крайней мере, первый аргумент), переданный.
The difference between onBlur vs onChange for React text inputs
When is one called versus the other?
Is there a situation where onChange would be called but onBlur would not be called?
Which one should you use to update React state?
Do they behave differently?
Let me see if I can answer these questions for you.
I’ll start off by showing you how each one of these events behave, and get triggered.
What is onBlur event in React
React onBlur behaves just like the native JavaScript version of blur.
Every time you get out of focus from the input field, the event will trigger.
Here’s how it looks like in React
It doesn’t matter if the value has changed or not, every time you get out of focus. The event will trigger.
What is onChange event in React
Does React onChange behave like it’s vanilla JavaScript version?
In the vanilla version, it sort of behaves like the blur event. It gets triggered after you’re out of focus from the input field.
The difference is, it ONLY triggers when the value is different.
So how does React onChange behave?
React onChange gets triggered on every keystroke on the keyboard.
Whether the value is different or not, it will get triggered.
onBlur or onChange? Why not both?
It really depends on what type of user experience you want to give.
Perhaps onChange would be a nice experience to give them a real-time update.
For example, let them know if they entered an invalid email address as they’re typing.
React is fast. You don’t have to worry about performance being an issue.
You’re not limited to just using one, you can always use them as a combination.
In the example above, I added a API call to check if the email address has been taken or if it’s available.
The API call is done on the onBlur event, that way I’m not hitting my servers on every keystroke.
Conclusion
Use React onChange if you want to give your users a real-time experience or to update React state.
Use React onBlur if you want to execute code after they’re out of focus or make API calls.
I like to tweet about React and post helpful code snippets. Follow me there if you would like some too!
Ruben Leija
I launched this blog in 2019 and now I write to 85,000 monthly readers about JavaScript. Say hi to me at Twitter, @rleija_.
Do you want more React articles?
Onblur react что это
HOC for Blur (Unfocus) event handling of React component
It is simple HOC function
which puts in your component two extra props
setBlurListener should be called when you want add events to document.
unsetBlurListener should be called when your want to remove events from document.
(. ) unsetBlurListener will be called in componentWillUnmount always.
How can you use it?
You should create new component:
Next, you can use this component in your App:
HOC function arguments
args | type | default | description |
---|---|---|---|
listenClick | bool | true | when true will add mousedown event for document |
listenTab | bool | true | when true will add keyup and keydown listeners for document to check Tab key press |
listenEsc | bool | true | when true will add keydown event for document to check Esc key is pressed |
debug | bool | false | when true will write debug messages to console |
autoUnset | bool | false | if true then unsetBlurListener will be called after callback action call once your component is unfocused or user will click outside of your component |
- Укусила оса что делать в домашних условиях
- одиннадцать лет супружеской жизни какая свадьба