前端input框文字最大值
针对中英文不同长度的问题
// 中文占2个字符,英文占1个字符
export function getStringLength(str: string) {
let strLength = 0;
const strLen = str.length;
for (let i = 0; i < strLen; i++) {
const charCode = str.charCodeAt(i);
// 大于255,表示双字节字符,需要长度+2
if (charCode > 255) {
strLength += 2;
} else {
strLength += 1;
}
}
return strLength;
}export const NAME_MAX_LIMIT = 40;
const [maxLength, setMaxLength] = useState(NAME_MAX_LIMIT);
const inputOnKeyUp = (
event: React.KeyboardEvent<HTMLInputElement>,
name: string
) => {
if (event.key === "Enter") {
const value = event.currentTarget.value;
}
};
const inputOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const remainingStingLength =
NAME_MAX_LIMIT - getStringLength(event.target.value);
setMaxLength(event.target.value.length + remainingStingLength);
};
<input
ref={inputRef}
onKeyUp={(e) => inputOnKeyUp(e, actorName)}
onChange={(e) => inputOnChange(e)}
maxLength={maxLength}
/>;针对输入法的处理
最后更新于