需求输入框,支持键盘输入和快捷键输入,UI如下“基于antd”:重点:键盘输入可以直接使用input的onChange事件,快捷键按键输入需要根据光标位置插入,插入后光标在新插入的字符后面。解决方案获取输入光标位置通过element.selectionStart获取光标位置。constinputDom=document.getElementById("input")constselectionStart=inputDom.selectionStart如图,此时的selectionStart为3.设置输入光标通过element.setSelectionRange()设置光标位置,前提是输入是集中的。inputDom.focus()//focus()是异步的,所以加上setTimeoutsetTimeout(()=>{constnextSelection=selectionStart+1inputDom.setSelectionRange(nextSelection,nextSelection)},0)element.setSelectionRange语法element.setSelectionRange(selectionStart,selectionEnd[,selectionDirection]);selectionStart:第一个选中字符的位置索引,从0开始。如果这个值大于元素的value长度,则认为它是value最后一个位置的索引。selectionEnd:最后选择的字符的下一个位置的索引。如果此值大于元素的值长度,则将其视为值最后位置的索引。selectionDirection:选择方向。forward/backward/none如果selectionStart与selectionEnd相同,则不选择任何内容,光标聚集在selectionStart/selectionEnd处。如果selectionEnd小于selectionStart,则不会选择任何内容,光标将聚焦在selectionEnd上。inputDom.setSelectionRange(0,4)如下图所示:完成代码0,'*','#',9]constInputPro=()=>{const[value,setValue]=useState('')constinputRef=useRef()consthandleSubmit=throttle(()=>{控制台。log('value',value)},3000)consthandleInputChange=e=>{setValue(e.target.value?.trim())}consthandleTagChange=val=>{constinputDom=inputRef.current?.input|}|{}letselectionStart=inputDom.selectionStartif(typeofselectionStart!='number'){selectionStart=value.length}constdata=`${value.slice(0,selectionStart,)}${val}${value。slice(selectionStart)}`if(data.length<=25){setValue(data)inputDom.focus()setTimeout(()=>{constnextSelection=selectionStart+1inputDom.setSelectionRange(nextSelection,nextSelection)},0)}}return(
