我已经创建了一个货币兑换应用程序.我的应用程序接受数字作为输入,运行良好.然而,当用户输入数字以外的内容或将输入字段留空时,我的应用程序不会执行任何操作.我希望它返回一个错误通知,说明需要提供一个数字.

这是我当前的代码,但它不起作用.它甚至不会在控制台上抛出错误,而是像提供了数字一样try 获取.

input.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 field on input.js:

<input type="number" placeholder="Enter the number you want to convert" className="px-4 py-2 rounded-xl" onChange={handleInputChange} />

Fetching part of 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
     });
 };

当我单击Convert按钮(触发上面的ConvertCurrency函数)时,当输入字段为空或非数字时,我的控制台抛出的内容:

获取http://localhost:3000/api/convert?convertFrom=ANG&amp;convertTo=ANG&amp;amount=

推荐答案

您犯的第一个错误是使用isNaN()来确定输入的是否是数字.正如您可以通过上面的链接阅读到的,它将用于检测值是否等于NaN,而不是任何数字.

我将使用正则表达式来避免在验证之前进行转换,因为即使输入类型为number,e.target.value也是一个字符串:

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(它只在输入失go 焦点后触发,而在Safari上,如果字段中有非数字值,则不会触发):

<input
    type="number"
    placeholder="Enter the number you want to convert"
    className="px-4 py-2 rounded-xl"
    onInput={handleInputChange}
/>

Javascript相关问答推荐

容器如何更改默认插槽中子项的显示?

React Hooks中useState的同步问题

获取表格的左滚动位置

fs. writeFile()vs fs.writeFile()vs fs.appendFile()

使用复选框在d3.js多折线图中添加或删除线条

在这种情况下,如何 for each 元素添加id?

WebRTC关闭navigator. getUserMedia正确

colored颜色 检测JS,平均图像 colored颜色 检测JS

如何用拉威尔惯性Vue依赖下拉?

html + java script!需要帮助来了解为什么我得到(无效的用户名或密码)

使用LocaleCompare()进行排序时,首先使用大写字母

如何在不影响隐式类型的情况下将类型分配给对象?

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

如何根据查询结果重新排列日期

如何在脚本编译后直接将RxJ模块导入浏览器(无需Angel、webpack、LiteServer)

重新呈现-react -筛选数据过多

react 路由如何使用从加载器返回的数据

JSON Web令牌(JWT)错误:RSA密钥对的签名无效

Google OAuth 2.0库和跨域开放程序的问题-策略错误

CSS网格使页面自动滚动