小编典典

在按Enter键后调用onChange事件

reactjs

我是Bootstrap的新手,并且一直遇到这个问题。我有一个输入字段,只要输入一个数字,onChange就会调用from函数,但是我希望在输入完整个数字后按“
Enter”键才能调用它。验证功能存在相同的问题-调用时间过早。

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
  //bsStyle: this.validationInputFactor(),
  placeholder: this.initialFactor,
  className: "input-block-level",
  onChange: this.handleInput,
  block: true,
  addonBefore: '%',
  ref:'input',
  hasFeedback: true
});

阅读 349

收藏
2020-07-22

共1个答案

小编典典

根据React Doc的说法,您可以听键盘事件,例如onKeyPressor onKeyUp,not onChange

var Input = React.createClass({
  render: function () {
    return <input type="text" onKeyDown={this._handleKeyDown} />;
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }
});

更新:使用React.Component

这是使用React.Component的代码,它执行相同的操作

class Input extends React.Component {
  _handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }

  render() {
    return <input type="text" onKeyDown={this._handleKeyDown} />
  }
}

这是jsfiddle

更新2:使用功能组件

const Input = () => {
  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      console.log('do validate')
    }
  }

  return <input type="text" onKeyDown={handleKeyDown} />
}
2020-07-22