我创建了一个货币转换器应用程序。我的应用程序接受数字作为输入并且运行良好。但是,当用户输入数字以外的内容或将输入字段留空时,我的应用程序不会执行任何操作。我希望它返回一个错误通知,澄清需要提供一个号码。
这是我当前的代码,但它不起作用。它甚至不会在控制台上抛出错误,而是尝试获取,就好像提供了数字一样。
输入.js:
import React, { useState } from 'react';
const Input = ({ dropdown, onChange, label, symbols }) => {
const arrOfSymbols = Object.keys(symbols);
arrOfSymbols.sort();
const [error, setError] = useState('');
const handleInputChange = (e) => {
const inputValue = e.target.value;
console.log('Input Value:', inputValue);
// Check if the input is empty or not a number
if (inputValue.trim() === '' || isNaN(inputValue)) {
// Set the error state
setError('Please enter a valid number.');
console.log('Error:', 'Please enter a valid number.');
} else {
// If the input is valid, clear the error state
setError('');
// Proceed with the provided onChange callback
onChange(inputValue);
}
};
input.js 上的输入字段:
<input type="number" placeholder="Enter the number you want to convert" className="px-4 py-2 rounded-xl" onChange={handleInputChange} />
获取index.js的部分内容:
// FETCH
const convertCurrency = () => {
const options = {
method: "GET",
url: "http://localhost:3000/api/convert",
params: { convertFrom, convertTo, amount },
};
axios.request(options).then(function (response) {
const { data } = response;
setConvertedAmount((data.result));
setError(null); // Clear any previous errors
}).catch(function (error) {
console.error(error);
setError('An error occurred during conversion.'); // Set an error message
});
};
当我单击“转换”按钮(触发上面的 ConvertCurrency 函数)而输入字段为空白或非数字时,我的控制台会抛出什么:
获取http://localhost:3000/api/convert?convertFrom=ANG&convertTo=ANG&amount=
isNaN()
来确定输入是否是数字。正如您所读到的,按照链接,它用于检测数字是否为 NaN
,而不是任何数字。我会使用像这样的正则表达式:
const handleInputChange = (e) => {
const inputValue = e.target.value;
console.log("Input Value:", inputValue);
const isNumberRegX = /^\d+$/;
// Check if the input is empty or not a number
if (!isNumberRegX.test(inputValue)) {
// Set the error state
setError("Please enter a valid number.");
console.log("Error:", "Please enter a valid number.");
} else {
// If the input is valid, clear the error state
setError("");
// Proceed with the provided onChange callback
onChange(inputValue);
}
};
其次,您需要使用
onInput
而不是 onChange
(它仅在输入失去焦点后触发,而在 Safari 上,如果失去焦点时字段中存在非数字值,则不会触发):
<input
type="number"
placeholder="Enter the number you want to convert"
className="px-4 py-2 rounded-xl"
onInput={handleInputChange}
/>