【问题标题】:React functional component onChange problemReact 功能组件 onChange 问题
【发布时间】: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


【解决方案1】:

Ciao 尝试像这样修改您的输入类型:

    <input name = {props.name}
           id = {props.name + '-id'}
           type = "number"
           className = {props.className}
           maxLength = {maxLength}
           value = {intValue}
           onChange = {handleChange}
    />

这应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2018-07-24
    • 2020-12-21
    • 1970-01-01
    • 2018-01-18
    • 2019-05-14
    相关资源
    最近更新 更多