【发布时间】:2020-08-17 21:27:30
【问题描述】:
我是 React 新手,我尝试创建一个简单的整数输入字段,只允许输入数字。
我的代码:
import React, {useState} from "react";
export const IntegerInput = props => {
const maxLength = props.maxLength ? parseInt(props.maxLength) : 10;
const [intValue, setIntValue] = useState(props.value);
const inputMask = new RegExp(/^[0-9\b]+$/);
function handleChange(e) {
let inputValue = e.target.value;
let isNumber = inputMask.test(inputValue);
let isEmpty = inputValue === '';
if (isEmpty || isNumber) {
console.log('Update value to: ' + inputValue);
setIntValue(inputValue);
} else {
console.log('Invalid input: ' + inputValue);
}
}
return (
<input name = {props.name}
id = {props.name + '-id'}
type = "text"
className = {props.className}
maxLength = {maxLength}
value = {intValue}
onChange = {handleChange}
/>
);
}
控制台没有错误,只有在需要时才调用setIntValue,但仍然可以在输入字段中输入任何字符。
可能是什么问题?
请注意,我想使用“文本”输入而不是“数字”,我在 React 方面遇到了问题,而不是 JavaScript。
【问题讨论】:
-
更改类型="数字"
-
由于问题被错误地关闭,我在这里写下解决方案。问题是道具中不存在值,因此组件变得不受控制。这篇文章帮助了我:link
标签: reactjs