我是 Bootstrap 的新手,并遇到了这个问题。我有一个输入字段,只要我输入一位数字,函数就会onChange
被调用,但我希望当我输入整个号码后按“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
});
根据反应文档 https://facebook.github.io/react/docs/events.html#keyboard-events,你可以监听键盘事件,比如onKeyPress
or 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 https://jsfiddle.net/wuct/d5exc1pw/.
更新 2:使用功能组件
const Input = () => {
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
console.log('do validate')
}
}
return <input type="text" onKeyDown={handleKeyDown} />
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)