gpt4 book ai didi

javascript - React/JavaScript 防止 KeyDown 键入(其他语言)

转载 作者:行者123 更新时间:2023-11-30 14:17:07 24 4
gpt4 key购买 nike

我使用 onKeyDown 的原因是打字语言是韩语。

我有几个输入,当用户输入超过 20 个字节时,我想阻止他们继续输入。

//this calculates bytes
const getByteLength = (s,b,i,c) => {
for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
return b;
}

.

handleLength = (e) => {
let currentBytes = getByteLength(e.currentTarget.value);
// checked : it calculates bytes successfully.
if (currentBytes > 20){
// checked : This is only working for English. When I type over than 20 bytes, this removes the lastest letter. but I still can type Korean.
e.currentTarget.value =
e.currentTarget.value.substring(0,e.currentTarget.value.length - 1);
}
}

<input onKeyDown={this.handleLength}>

最佳答案

您应该将输入的值保存在 state 变量中:

类 Foo 扩展组件 { 状态={ 值(value): '' };

handleLength = (e) => {
let currentBytes = getByteLength(e.currentTarget.value);
// checked : it calculates bytes successfully.
let value = e.currentTarget.value;
if (currentBytes > 20){
value = e.currentTarget.value
.substring(0,e.currentTarget.value.length - 1);
}
this.setState({ value });

然后在您的输入中使用状态中的值:

<input value={this.state.value} onKeyDown={this.handleLength} />

关于javascript - React/JavaScript 防止 KeyDown 键入(其他语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53405603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com