需求:只能输入正数,最多支持两位小数,超过禁止输入并在输入框下方提示文案。
方案一:使用antd自带的InputNumber组件 1. 设置precision:不能限制输入,还会四舍五入。 2. 设置formatter、配合自定义校验方法。缺陷:多次按相同的数会出现第三位小数。
方案二:使用普通的Input,加上type='number'
import { Form, Input } from 'antd';
const customValidatorFn = (prop, name) => ({
validator() {
let result = prop?.getFieldValue(name);
// 小数处理
if (`${result}`.indexOf('.') > -1) {
const integer = `${result}`?.split('.')[0];
const decimals = `${result}`?.split('.')[1];
const dotLength = decimals.length;
if (dotLength > 2) {
let newData = parseFloat(`${integer}.${decimals.substring(0, 2)}`);
if (newData < 0) {
newData = 0;
}
prop.setFields([{ name, value: newData }]);
return Promise.reject('最多支持两位小数');
} else {
return Promise.resolve();
}
}
// 其他情况取绝对值
prop.setFieldsValue({ [name]: Math.abs(parseFloat(result)) });
// 不输入处理
return Promise.resolve();
},
});
<Form.Item
name="number"
label="数字"
rules={[
(prop) => customValidatorFn(prop, 'number'),
]}
>
<Input
type="number"
onWheel={(e) => (e.target as HTMLInputElement).blur()} //防止鼠标滚动导致数值变化
min={0}
placeholder="请输入"
addonAfter={<span>%</span>}
/>
</Form.Item>
// 去除输入框后面图标
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
margin: 0 !important;
-webkit-appearance: none !important;
}