我想检查输入文本类型的值是数字还是字符串,如下所示:
<input
type="text"
onChange={(e) => {
const value = e.target.value;
console.log(typeof value);
}}
/>
但是当我输入文本或数字时,它在两种情况下都会在控制台记录字符串。
如何在 React js 中检查值是否为带有输入类型文本的数字?
最佳答案
最简单的方法是将字符串转换为数字,然后检查它是否有效。因为输入的值始终是 string
,即使您使用 type="number"
,但如果您只想将数字作为输入,最好使用它。
您可以使用 isNaN(+value)
。这里 +
会将字符串转换为数字。
<input
type="text"
onChange={(e) => {
const value = e.target.value;
console.log(!isNaN(+value)); // true if its a number, false if not
}}
/>
部分测试用例:
console.log(!isNaN(+"54"));
console.log(!isNaN(+"23xede"));
console.log(!isNaN(+"test"));
Note: As mentioned this is a simple way, there can be workarounds to bypass this, for a robust solution you can have a look here: Check whether variable is number or string in JavaScript
关于javascript - 如何检查输入的值是 react js中的数字还是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68007900/