使用 onKeyDown 过滤掉所有字符并将其小写 (ev: React.KeyboardEvent<HTMLElement>)
Filter out and lower case all characters using onKeyDown (ev: React.KeyboardEvent<HTMLElement>)
我正在使用 TagPicker
事件 onKeyDown
签名 (ev: React.KeyboardEvent<HTMLElement>) => void
有什么方法可以使用此事件只允许使用小写字母和破折号 -
符号吗?理想情况下,我想自动将大写字母转换为小写字母。
我找到了一个解决方案,TagPicker
有一个 inputProps
属性可以连接到输入事件。一旦我发现了这一点,这个任务就变得相当容易了:
<TagPicker onResolveSuggestions={this.onResolveSuggestions}
..
inputProps={{
onBlur: () =>
console.log("onBlur called"),
onFocus: () =>
console.log("onFocus called"),
"aria-label": "Tag Picker",
onKeyPress: (e) =>
{
var charInput = e.charCode;
// no modifier key and no lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey &&
!(charInput >= 97 && charInput <= 122)) {
//UPPERCASE => lowercase
if((charInput >= 65) && (charInput <= 90)){
charInput=charInput+32;
}
//UNDERSCORE => dash
if((charInput == 95)){
//DASH
charInput=45;
}
if((charInput >= 97 && charInput <= 122) || charInput == 45) {
const start = e.currentTarget.selectionStart;
const end = e.currentTarget.selectionEnd;
const isPrevCharDash = (start > 0 && e.currentTarget.value.charAt(start-1) === "-");
if(!((start == 0 || isPrevCharDash) && charInput == 45)){
e.currentTarget.value = e.currentTarget.value.substring(0, start) + String.fromCharCode(charInput) + e.currentTarget.value.substring(end);
e.currentTarget.setSelectionRange(start+1, start+1);
}
}
e.preventDefault();
}
}
}}
/>
这里是demo.
我正在使用 TagPicker
事件 onKeyDown
签名 (ev: React.KeyboardEvent<HTMLElement>) => void
有什么方法可以使用此事件只允许使用小写字母和破折号 -
符号吗?理想情况下,我想自动将大写字母转换为小写字母。
我找到了一个解决方案,TagPicker
有一个 inputProps
属性可以连接到输入事件。一旦我发现了这一点,这个任务就变得相当容易了:
<TagPicker onResolveSuggestions={this.onResolveSuggestions}
..
inputProps={{
onBlur: () =>
console.log("onBlur called"),
onFocus: () =>
console.log("onFocus called"),
"aria-label": "Tag Picker",
onKeyPress: (e) =>
{
var charInput = e.charCode;
// no modifier key and no lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey &&
!(charInput >= 97 && charInput <= 122)) {
//UPPERCASE => lowercase
if((charInput >= 65) && (charInput <= 90)){
charInput=charInput+32;
}
//UNDERSCORE => dash
if((charInput == 95)){
//DASH
charInput=45;
}
if((charInput >= 97 && charInput <= 122) || charInput == 45) {
const start = e.currentTarget.selectionStart;
const end = e.currentTarget.selectionEnd;
const isPrevCharDash = (start > 0 && e.currentTarget.value.charAt(start-1) === "-");
if(!((start == 0 || isPrevCharDash) && charInput == 45)){
e.currentTarget.value = e.currentTarget.value.substring(0, start) + String.fromCharCode(charInput) + e.currentTarget.value.substring(end);
e.currentTarget.setSelectionRange(start+1, start+1);
}
}
e.preventDefault();
}
}
}}
/>
这里是demo.