ant-design中textArea组件获取光标位置,插入表情之后自动将光标移至文本的最后

2023-11-13

目前的需求是要设置一段文本,但是文本里可以插入微信表情,需要实现在插入表情之后光标位置自动移到当前文本的最后。

效果图:

实现代码:

textArea组件:

<TextArea
   {...restProps}
   value={value}
   onChange={handleChange}
   ref={_ref => {
       if (ref) {
           ref.current = _ref
       }
       textareaRef.current = _ref
    }}
/>

 当点击表情之后(react的版本为16):

// 参数emoji类似于[憨笑]这种文本
const handleEmojiClick = emoji => {
        const currentTextArea = textareaRef.current.resizableTextArea.textArea
        setTimeout(() => {
            currentTextArea.focus() // setTimeout这个focus才生效
            const caretPos = currentTextArea.selectionStart
            const textAreaTxt = currentTextArea.value
            // https://stackoverflow.com/questions/23892547/what-is-the-best-way-to-trigger-onchange-event-in-react-js
            const nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set
            nativeTextareaValueSetter.call(currentTextArea, textAreaTxt.substring(0, caretPos) + emoji + textAreaTxt.substring(caretPos))
            const event = new Event('input', { bubbles: true })
            currentTextArea.dispatchEvent(event)
            currentTextArea.selectionStart = caretPos + emoji.length
            currentTextArea.selectionEnd = caretPos + emoji.length
        }, 10)
    }

https://www.cnblogs.com/katydids/p/12430581.html  看了下这位博主的实现方法,供参考

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ant-design中textArea组件获取光标位置,插入表情之后自动将光标移至文本的最后 的相关文章

随机推荐