我在 ReactJS 中有一个输入字段:
<input
type="number"
onKeyPress={handleKeyPress}
maxLength={3}
min="0"
max="999"
step=".1"
onPaste={handlePaste}
pattern="[0-9]*"
/>
以下是相关函数:
function handleKeyPress(e) {
console.log(e.target.value);
if (e.target.value.length >= e.target.maxLength) {
e.target.value = e.target.value.slice(0, e.target.maxLength);
e.preventDefault();
return;
}
const key = e.key;
if (!allowChars(key)) {
e.preventDefault();
}
}
function allowChars(charValue) {
const acceptedKeys = '0123456789.';
return acceptedKeys.indexOf(charValue) > -1;
}
function handlePaste(event) {
event.preventDefault();
}
当我记录 e.target.value
并在输入字段中输入 ....
时,小数点不会记录。为什么是这样?我怎样才能让他们注册?
谢谢。
最佳答案
您的 pattern
属性不允许 .
。将其更改为 pattern="[0-9.]*"
。
不过,可能没有必要使用pattern
。由于它是 type="number"
,因此它应该只允许有效的数字,这使得模式变得多余。
关于javascript - 如何获取输入数字字段中的小数以注册其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48754622/