在原生 input 中,maxlength 只在 type 为 text, search, url, tel, email, password 时生效;
如果需要对 number 类型的输入框进行限制,可以通过
- max
- min 属性
import React, { useState, useEffect } from "react";
// import PropTypes from "prop-types";
import { Input, NumberKeyboard } from "antd-mobile";
Mobile.propTypes = {};
function Mobile() {
const [value, setValue] = useState("");
const [visible, setVisible] = useState(false);
useEffect(() => {
setVisible(true);
}, []);
// 点击输入时
const onInput = (val: string) => {
setValue(v => {
const result = v + val;
if (result.length > 5) {
return result.slice(0, 5)
}
return result;
});
};
// 点击删除按钮
const onDelete = () => {
setValue(v => v.slice(0, v.length - 1));
};
// 关闭键盘
const onClose = () => {
setVisible(false);
};
return (
<div>
{/* 设置 "readonly" 属性,将无法在输入框中输入任何内容
如果还设置了 "onChange" 事件,该事件不起作用。
因为 "readonly" 属性会禁用输入框的输入,导致无法触发 "onChange" 事件
*/}
<div
onClick={() => {
console.log('readOnly click')
setVisible(true)
}}
>
{/* 添加 readOnly 阻止原生键盘弹出 */}
<Input
placeholder="请输入内容"
value={value}
readOnly
/>
</div>
<NumberKeyboard
visible={visible}
onClose={onClose}
onInput={onInput}
onDelete={onDelete}
// title='数字键盘'
customKey="."
confirmText='确定'
/>
</div>
);
}
export default Mobile;
纯数字键盘
PC端点击无效,需要在移动设备上点击
import { Card } from "antd";
import { NumberKeyboard } from "antd-mobile";
function App() {
const [inputValue, setInputValue] = useState('');
// 点击删除按钮
const onDelete = () => {
setInputValue(v => v.slice(0, v.length - 1));
};
// 点击输入时
const onInput = (val: string) => {
setInputValue(v => {
const result = v + val;
if (result.length > 5) {
return result.slice(0, 5);
}
return result;
});
};
return (
<div className="__inner__">
<Card bordered={false}>
<NumberKeyboard
visible
onInput={onInput}
onDelete={onDelete}
customKey="."
showCloseButton={false}
forceRender
getContainer={null}
/>
</Card>
</div>
)
}
Input.readonly
添加 readOnly 阻止原生键盘弹出
设置 “readonly” 属性,将无法在输入框中输入任何内容,
�如果还设置了 “onChange” 事件,该事件不起作用。
因为 “readonly” 属性会禁用输入框的输入,导致无法触发 “onChange” 事件
<Input
placeholder="请输入内容"
value={value}
readOnly
/>
less
.__inner__ {
.adm-popup,
.adm-popup-body {
position: static;
}
.adm-number-keyboard-main {
margin-right: -8px;
padding: 8px;
}
.adm-number-keyboard-key {
flex: 1 1 30%;
height: 56px;
margin-bottom: 8px;
margin-right: 3.333%;
font-size: 32px;
border-radius: 12px;
border: none;
gap: 8px;
}
}