简体   繁体   中英

How to put/paste the content where cursor is there in content editable div

I am a newbie on react. I have a content editable div. What I want is Make a button, on button click -> "HEY" word will be added. Let's say my content length is 100, and I have clicked on initial 5 character and giving the space and click my paste button. So the "HEY" content will be append in that position.

My code:

renderValue = () => {
 var textNode = document.createTextNode("HEY");
      let p1 = document.getElementById('work').focus();
      p1.appendChild(textNode)
}

render(){
<button onClick={() => this.renderValue()}>Paste</button>
<div id="work" onClick={(e)=>e.stopPropagation()}  
contentEditable 
onInput={this.emitChange}
dangerouslySetInnerHTML={{__html: this.props.html}}
>
</div>
}

I have tried to append the text but not getting luck.

Anny help is really appreciated. Thanks in advance.

You can use document.execCommand() with insertText command. Like

document.execCommand("insertText", false, "HEY!!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM