反应和文本输入-使用onBlur或onChange吗? [英] React and text inputs - use onBlur or onChange?

查看:46
本文介绍了反应和文本输入-使用onBlur或onChange吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理带有大约6个文本输入字段的表单.

I am working on a form with about 6 text input fields.

要将值保存到我的状态,最好是 onBlur onChange ?

To save the values to my state, is it better to do so onBlur or onChange?

例如onChange

For example with onChange,

onChangeTextInput = ({ name, value }) => {
    this.setState(state => ({
      ...state,
      form: {
        ...state.form,
        [name]: value
      }
    }));
  };

每次按键都将更新状态.当我使用React工具显示更新"时,由于该字段被更新了多少次,我看到了大量的更新.

Each time a key is pressed it will update the state. When I use the react tools "show update" I see a ton of updates because of how many times the field is updated.

我应该使用onBlur来避免这种情况吗?还是有一种方法可以分批"状态更新?

Should I use onBlur instead to avoid this? Or is there a way to "batch" the state update?

谢谢

推荐答案

所以这取决于您想要的场景是什么:)

So it depends what you want the scenario to be :)

OnBlur仅在用户单击字段外时触发,如果那不是您的正确用户体验,我的建议是使用输入延迟(也称为反跳)!拨好电话后就非常酷.

OnBlur will only trigger once the user clicks out of the field, if that isn't the correct user experience for you, my suggestion would be to use an input delay (also known as debouncing)! very cool once you get it dialed in nicely.

我不会直接为您提供代码,因为它是将来正确理解的非常有用的工具,但请查看:

I won't give you the code outright because it's a really useful tool to understand properly in the future but check out:

从'throttle-debounce'导入{debounce};

曾经有很多这样的软件包,但是它的作用是在构造函数中的一个函数上设置了一个超时:

There are many packages like this once, but what it does is set's a timeout on a function in your constructor:

this._updateValues = debounce(500,this._updateValues);

每次调用此函数都将等待500毫秒,然后再运行,但是如果在该时间段内再次调用该函数,计时器将被重置:)

Every time this function is called it will wait 500 milliseconds before running, but if it is called again within that time frame, the timer will be reset :)

这篇关于反应和文本输入-使用onBlur或onChange吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆