onChange or onBlur to change the state in ReactJs?

安稳与你 提交于 2020-05-15 06:16:20

问题


//Assume am changing state in handleChange function.

In case of onChange event state will update every character change.

  <input
    type="text"
    name="name"
    onChange={this.handleChange}
    id="name"
  />

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"
 />

which approach is best to update the state in React and why ?


回答1:


This is actually a trade-off decision.

I assume that, in your event handler function, you are calling React setState() to update your states.

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.

  • Choose onChange(): If you need the latest state immediately after input change, for example:

Search suggestion after each input (like Google search box)

Validating input after every change

  • 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


Also think of this scenario:

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.

So, my unofficial suggestion is to use onChange whenever possible and use onBlur only when you need final changed value.




回答2:


You can choose either of methods based on your requirement.

For example, if you need to perform validations to a field while the input is being entered , you could choose onChange.

Setting the state with onChange would be called every-time you enter something to field which leads to re-render the input again.

onBlur would call the setState only when you focus-out the input.

In my Opinion, onBlur would be good option , but it totally depends on the requirement which we have.



来源:https://stackoverflow.com/questions/52553251/onchange-or-onblur-to-change-the-state-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!