admin管理员组文章数量:1186154
I'm making an Autocomplete
component in React which shows a dropdown of suggested completions as you type into a text box. Clicking on a suggestion should fire a callback, and the dropdown should disappear when the text box loses focus. The problem is that the onBlur
event for the text box fires before the onClick
event for the the suggestion, so what happens is:
- Click on item
- Text box loses focus =>
this.setState(this.getInitialState())
- Component rerenders, with no suggestions box because state has been cleared
- The click event lands on the empty space where the suggestion item used to be
What's the best way to solve this without resorting to a hack like onBlur={() => setTimeout(() => this.setState(this.getInitialState()), 100)}
?
I'm making an Autocomplete
component in React which shows a dropdown of suggested completions as you type into a text box. Clicking on a suggestion should fire a callback, and the dropdown should disappear when the text box loses focus. The problem is that the onBlur
event for the text box fires before the onClick
event for the the suggestion, so what happens is:
- Click on item
- Text box loses focus =>
this.setState(this.getInitialState())
- Component rerenders, with no suggestions box because state has been cleared
- The click event lands on the empty space where the suggestion item used to be
What's the best way to solve this without resorting to a hack like onBlur={() => setTimeout(() => this.setState(this.getInitialState()), 100)}
?
2 Answers
Reset to default 28Found a very simple solution: the mousedown
event fires for the result item being clicked before blur
fires for the text input. Furthermore if the mousedown
callback calls event.preventDefault()
, it prevents the blur
event from firing for the input, but doesn't prevent the future click
event from firing on the result item once mouseup
occurs. So, long story short, simply adding this handler to the result item fixes everything: onMouseDown={event => event.preventDefault()}
Looks like there's an open source Autocomplete
component and they had to tackle this exact problem.
本文标签: javascriptDelayed onBlur callbackStack Overflow
版权声明:本文标题:javascript - Delayed onBlur callback - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738327527a2075422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论