如果您想保持输入type='number'
(可能用于移动设备触发数字键盘),您应该使用onInput
而不是onChange
捕获您的事件更改。
使用onInput
修复了一个错误,即在数字输入中输入文本会绕过我在onChange
. 一旦我修复了要在onInput
其中调用的此函数,它就会在所有情况下触发。
这是我正在做的一个例子:
<input
type='number'
id={`player${index}Score`}
className='form-control'
pattern='[0-9]{0,5}'
onInput={(event) => this.enterScore(event, index)}
value={this.props.scoreLabel(this.state.scores[index])}
/>
我希望这有帮助!
编辑 - 08-03-2018:
我想出了一个更好的解决方案。在输入组件本身中使用 type='tel' 和模式正则表达式。
我如何连接它的螺母和螺栓在这里:
class Input extends React.Component {
state = {message: '3'};
updateNumber = (e) => {
const val = e.target.value;
// If the current value passes the validity test then apply that to state
if (e.target.validity.valid) this.setState({message: e.target.value});
// If the current val is just the negation sign, or it's been provided an empty string,
// then apply that value to state - we still have to validate this input before processing
// it to some other component or data structure, but it frees up our input the way a user
// would expect to interact with this component
else if (val === '' || val === '-') this.setState({message: val});
}
render() {
return (
<input
type='tel'
value={this.state.message}
onChange={this.updateNumber}
pattern="^-?[0-9]\d*\.?\d*$"
/>
);
}
}
ReactDOM.render(<Input />, document.getElementById('main'));
我在这里有一个在Codepen 上工作的例子