[英]React: select event in div with multiple span elements
I have a React component with parsed text: 我有一个带有解析文本的React组件:
The html structure is like: html结构类似于:
<div>
<span>It's a </span>
<span className="highlight-text">cat</span>
</div>
How I can have a event listener which enable I pass all selected text within this div? 我如何拥有一个事件侦听器,使我可以在此div中传递所有选定的文本? For example, if I select "a ca", the event listener can get e.target.value = "a ca".
例如,如果我选择“ ca”,则事件侦听器可以获取e.target.value =“ ca”。
It is possible the highlight part will be repeating within the full text, for example: 高亮部分可能会在全文中重复,例如:
<div>
<span>It's a slim cat, not a fat </span>
<span className="highlight-text">cat</span>
</div>
In this case, the selection listener will get 2nd part string, start position of whole text. 在这种情况下,选择侦听器将获得第二部分字符串,即整个文本的开始位置。
This is the first thing that comes to mind. 这是想到的第一件事。
// Example impl
<Component text="This is a cat" highlight="is a" />
// Component render
render() {
const {
text,
highlight,
} = this.props;
// Returns the start index for your high light string
// in our example 'is a' starts at index 5
const startHighlightTextIdx = text.search(highlight);
// Create a substring for the first part of the string
// ie: 'This is '
const startText = text.substring(0, startHighlightTextIdx);
// Create a substring for the last part of the string
// For this substr we want to start where our startHighlightTextIdx starts
// and we want to add the length of the highlighted string
// in order to ignore the highlighted string
// ie: start at index 5 + 4 (highlight text length) so substr(9) to end
const endText = text.substring(
startHighlightTextIdx + highlight.length,
);
<div>
<span>{startText}</span>
<span className="highlight-text">{highlight}</span>
<span>{endText}</span>
</div>
}
v2:
// This might be a cleaner solution
// explode by the hightlight string and grab index 0 and last
// this outputs ["This ", " cat"]
const textParts = text.split(highlight);
const startText = textParts[0];
const endText = textParts[1];
I got one answer myself, in order to get the selected text, I can just use window.getSelection(). 我自己得到了一个答案,为了获得所选文本,我可以只使用window.getSelection()。
But not sure if there's a risk 但不确定是否有风险
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.