[英]I want to select specific text from textarea and make it bold, italic or make an hyperlink in reactjs
I am using textarea for making an editor and wanna implement bold, italic or hyperlink to a selected text. 我正在使用textarea进行编辑,并想要对所选文本实施粗体,斜体或超链接。 Right now, if I am making it bold or italic, the effect is in entire box. 现在,如果我将其设为粗体或斜体,则效果会显示在整个框中。 I wanna restrict it and keep it to selected text only. 我想将其限制为仅保留选定的文本。 I am able to get the selected text from the textarea, I am not able to make it bold or italic or put a link on the selected task as document.execCommand doesn't work in reactjs. 我可以从文本区域中获取选定的文本,我无法使其变为粗体或斜体,或者无法在所选任务上添加链接,因为document.execCommand在reactjs中不起作用。
I am getting the selected text from textarea through getSelectionTxt() function but with this text_to_hyperlink it is replacing the entire text with anchor tags and url. 我正在通过getSelectionTxt()函数从textarea获取选定的文本,但是使用此text_to_hyperlink,它将用锚标记和url替换整个文本。
I want to have that link to be associated with the selected tags. 我希望该链接与所选标签相关联。 I am invoking this text_to_hyperlink with a button. 我正在通过按钮调用此text_to_hyperlink。
text_to_hyperlink=()=> {
var text_entry = document.getElementById('textArea');
var text_selected = this.getSelectionTxt();
var url = document.getElementById("url").value;
text_entry.value = '<a href="' + url + '">' + text_selected + '</a>' ;
}
getSelectionTxt =() => {
var text = "";
var activeEl = document.activeElement;
if (activeEl == "textarea") {
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
var url = document.getElementById("url").value;
return text;
}
<textarea
id="textArea"
contenteditable="true"
rows="10"
value={this.state.value}
onClick={this.getSelectionTxt}
onChange={this.handleChange}
/>
You can't do this with a textarea
element: they support plaintext only, and not HTML. 您不能使用textarea
元素执行此操作:它们仅支持纯文本,不支持HTML。 You will have to use a different element with contenteditable="true"
. 您将必须使用带有contenteditable="true"
的其他元素。 I prefer div
, but others work as well. 我更喜欢div
,但其他人也可以。
A textarea
element cannot render HTML. textarea
元素无法呈现HTML。 You could either use a WYSIWYG editor compatible with React like one of these: 您可以使用与React兼容的WYSIWYG编辑器,例如以下一种:
1) Medium-Editor - https://github.com/yabwe/medium-editor 1)中型编辑器-https: //github.com/yabwe/medium-editor
2) Draft.js - https://draftjs.org/ 2)Draft.js- https: //draftjs.org/
or use a <div>
with contentEditable=true
and render HTML inside of it. 或使用带有contentEditable=true
的<div>
并在其中呈现HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.