在Antd中,使用Input组件时,如果同时设置了maxLength和type为"number",会发生冲突。这是因为当type设置为"number"时,输入框只能输入数字,而maxLength属性是用于限制输入框的最大字符数的。

要解决这个问题,可以通过自定义输入限制来实现。可以使用Input组件的onInput事件,在事件处理函数中对输入进行限制,保证输入框只能输入数字且不超过指定长度。

以下是一个示例代码:

import React, { useState } from "react";
import { Input } from "antd";

const NumberInput = () => {
  const [value, setValue] = useState("");

  const handleInput = (e) => {
    const inputValue = e.target.value;
    const maxLength = 10; // 设置最大长度为10

    // 只保留数字并截取指定长度
    const filteredValue = inputValue.replace(/[^\d]/g, "").slice(0, maxLength);

    setValue(filteredValue);
  };

  return <Input type="text" value={value} onInput={handleInput} />;
};

export default NumberInput;

在这个示例中,我们使用了useState来保存输入框的值。在handleInput函数中,我们首先使用正则表达式/[^\d]/g过滤掉非数字字符,然后使用slice方法截取指定长度的字符串。最后,将过滤后的值更新到useState中,实现了限制只能输入数字且不超过指定长度的效果。

通过自定义输入限制,我们可以解决Antd Input组件的maxLength和type为"number"冲突的问题

antd Input输入框 maxLength和typenumber冲突怎么解决

原文地址: https://www.cveoy.top/t/topic/iKAb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录