javascript 反应:不要对 onChange 事件使用 keyUp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23997860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:57:50  来源:igfitidea点击:

React: Don't use keyUp for onChange events

javascripteventsreactjskeyup

提问by Kyle Hotchkiss

Is it possible to have React fire the onChangeevent after the focus on an element is lost as opposed to having it on keyUp(currently, onChangeis an abstraction of any event that manipulates the field value)? keyUpis a little slow for me, and I think it may help the mobile expereince with what I'm building to switch the firing of that to after the field is focused.

是否有可能让 ReactonChange在失去对元素的焦点后触发事件而不是将其打开keyUp(目前,onChange是任何操作字段值的事件的抽象)?keyUp对我来说有点慢,我认为这可能有助于我正在构建的移动体验将其切换到聚焦领域之后。

回答by captray

Are you looking for something like this?

你在寻找这样的东西吗?

JS Fiddle

JS小提琴

I may be interpreting what you're asking for incorrectly, but you should be able to get your values via e.target.value or through using a ref, like:

我可能会错误地解释您的要求,但您应该能够通过 e.target.value 或通过使用 ref 获取您的值,例如:

<input type="text" ref="myValue" onBlur={this.handleChange} />

and then in your handleChange function you'd have something like this:

然后在你的 handleChange 函数中你会有这样的东西:

handleChange: function()
{
    var theValue = this.refs.myValue.getDOMNode().value;
    //setState, etc. here
}

回答by tungd

You could build your own component that support this behavior, for example:

您可以构建自己的支持此行为的组件,例如:

var ChangeOnBlurInput = React.createClass({
  render: function() {
    var options = this.props;
    options.onBlur = options.onChange;
    // You can also use `transferPropsTo` here, but I've heard it's deprecated
    return React.DOM.input.call(React.DOM, options);
  }
});

React.renderComponent(
  ChangeOnBlurInput({
    value: "Nice", 
    onChange: function(e) { alert(e.target.value) } }),
 document.body);

And use it instead of React.DOM.inputwherever you want.

并使用它而不是React.DOM.input您想要的任何地方。