onChange或onBlur更改ReactJs中的状态? [英] onChange or onBlur to change the state in ReactJs?
问题描述
//假设正在更改handleChange
函数中的state
.
//Assume am changing state
in handleChange
function.
在onChange
的情况下,事件状态将更新每个字符更改.
In case of onChange
event state will update every character change.
<input
type="text"
name="name"
onChange={this.handleChange}
id="name"
/>
在onBlur
情况下,事件状态将在离开输入字段后单次更新.
In case of onBlur
event state will update at single shot after leaving input fields.
<input
type="text"
name="name"
onBlur={this.handleChange}
id="name"
/>
哪种方法最适合更新React
中的state
,为什么?
which approach is best to update the state
in React
and why ?
推荐答案
这实际上是一个权衡的决定.
我假设在事件处理程序函数中,您正在调用React setState()
来更新状态.
I assume that, in your event handler function, you are calling React setState()
to update your states.
对setState的调用是异步的.它创建一个待处理状态转换". (有关更多详细信息,请参见此处).它的速度非常快,并且具有简化器,可以仅更新已更改的节点.因此,您实际上不需要考虑性能.
A call to setState is asynchronous. It creates a "pending state transition." (See here for more details). It is really fast and has a reducer to update only changed nodes. So you really don't need to think about performance.
- 选择
onChange()
:如果在输入更改后立即需要最新状态,例如:
- Choose
onChange()
: If you need the latest state immediately after input change, for example:
每次输入后的搜索建议(如Google搜索框)
Search suggestion after each input (like Google search box)
每次更改后验证输入
- 选择
onBlur()
:如果仅在最终输入的末尾需要最新状态,例如: - Choose
onBlur()
: If you only need the latest state at the end of the final input, for example:
每次更改都会触发获取事件,该事件会检查输入的用户名或电子邮件是否存在
Every change triggers a fetch event that checks if entered username or email exists
也考虑这种情况:
最终用户填写了所有3个注册输入(名称,密码和电子邮件),但是在最后一次输入(即电子邮件)之后,他/他直接单击了发送按钮(这触发了您的注册方法,而没有更新的电子邮件值/状态) ).
由于setState
是异步的,并且尚未更新电子邮件状态,因此您可能会遇到有关空电子邮件输入的问题.
The end-user filled all 3 registration inputs (name, password and email), but after the last input i.e. email, s/he directly clicked the send button (which has fired your signup method without the updated email value/state).
Since setState
is asynchronous and has not updated the email state yet, you might face problems about null email inputs.
因此,我的非正式建议是,尽可能使用onChange
,并且仅在需要最终更改的值时使用onBlur
.
So, my unofficial suggestion is to use onChange
whenever possible and use onBlur
only when you need final changed value.
这篇关于onChange或onBlur更改ReactJs中的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!