0

我正在使用带有签名TagPicker的事件onKeyDown(ev: React.KeyboardEvent<HTMLElement>) => void

有没有办法可以使用此事件只允许小写字母和破折号-?理想情况下,我想自动将大写字母转换为小写字母。

4

1 回答 1

0

我已经找到了一个解决方案,它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();
            }
        }
    }}
/>

这是一个演示

于 2019-06-06T14:55:33.883 回答