目前的需求是要设置一段文本,但是文本里可以插入微信表情,需要实现在插入表情之后光标位置自动移到当前文本的最后。
效果图:
实现代码:
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 看了下这位博主的实现方法,供参考