问题描述
我已经尝试过寻找答案,但是大多数都在React的上下文之外,其中 onChange
在模糊时触发。
I've tried searching around for an answer to this, but most of them are outside the context of React, where onChange
triggers upon blur.
在执行各种测试时,我似乎无法分辨出这两个事件有何不同(应用于文本区域时)。谁能对此有所启发?
In performing various tests, I can't seem to tell how these two events are different (when applied to a textarea). Can anyone shed some light on this?
推荐答案
似乎没有真正的区别
出于某种原因,应将 Component.onChange
的侦听器附加到DOM element.oninput
事件。参见文档中有关表单的注释:
It seems there is no real difference
React, for some reason, attaches listeners for Component.onChange
to the DOM element.oninput
event. See the note in the docs on forms:
React docs - Forms
有更多的人对此行为感到惊讶。有关更多详细信息,请参阅React问题跟踪器上的此问题:
There are more people that are surprised by this behavior. For more details, refer to this issue on the React issue tracker:
Document how React's onChange relates to onInput #3964
对该问题的评论引用:
为了进行验证,有时我们不想显示验证错误,直到他们完成了打字。或者,也许我们只是不想在每次击键时都重新渲染。现在唯一的方法是使用onBlur,但现在我们还需要检查值是否已手动更改。
For validation, sometimes we don't want to show validation errors until they're done typing. Or maybe we just don't want a re-render on every keystroke. Now the only way to do that is with onBlur but now we also need to check that the value has changed manually.
这没什么大不了的,但是在我看来,这就像React
It's not that big of a deal, but it seems to me like React threw away a useful event and deviated from standard behaviour when there was already an event that does this.
我已经同意100%的评论了……但是我想现在更改它会带来比解决方案更多的问题,因为已经编写了太多依赖此行为的代码。
I agree 100% with the comment... But I guess changing it now would bring more problems than it solves since so much code had already been written that relies on this behavior.
反应不是官方Web API集合的一部分
即使React是基于JS构建的,并且已经获得了巨大的采用率,因为React存在一种技术,可以将很多功能隐藏在自己的技术下(相当小)API。一旦在事件系统中显而易见的地方出现了,那么与标准DOM事件系统完全不同的是地下发生了很多事情。不仅根据哪个事件执行了什么操作,还根据何时允许数据保留在事件处理的哪个阶段。您可以在此处了解更多信息:
Even though React is built on top of JS, and has seen a huge adoption rate, as a technology React exists to hide a whole lot of functionality under its own (fairly small) API. Once area where this is obvious is in the event system, where there's a lot going on under the surface that's actually radically different from the standard DOM event system. Not just in terms of which events do what, but also in terms of when data is allowed to persist at what stage of the event handling. You can read more about that here:
React Event System
这篇关于在React中,onChange和onInput有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!