我有一个显示一些跨度的React应用程序:
<span>Hello</span> <span>my</span> <span>name</span> <span> is </span> ...
..然后获取所选值,或突出显示文本等。 我如何在React中做到这一点?我不确定要使用哪些事件处理程序以及如何掌握当前选择!一个最小的例子或提示将不胜感激!
答案 0 :(得分:5)
使用onMouseUp
和onDoubleClick
事件来检测调用方法,该方法将使用JavaScript Selection API确定选择。
使用window.getSelection()
获取选择对象。
要获取选定的文本,请使用window.getSelection.toString()
。
要获取用于渲染弹出菜单的选定文本区域的坐标,请使用selection.getRangeAt(0).getBoundingClientRect()
。
作为示例实现,请看一下react-highlight库。
答案 1 :(得分:3)
我认为这是正确的方法...
v.size()
答案 2 :(得分:2)
没有特定于React的解决方案。只需使用window.getSelection API。
要输出突出显示的文字,请运行window.getSelection.toString()
答案 3 :(得分:0)
由于此bug in Firefox,我无法使其与
<div id="st-container">
<div class="ui st-menu st-effect-1" id="menu1">
</div>
<div class="cv st-menu st-effect-1" id="menu2">
</div>
<div class="click" style="position: relative; left: 50%;" data-effect="st-effect-1">Menu1</div>
<div class="click" style="position: relative; left: 50%;" data-effect="st-effect-1">Menu2</div>
</div>
,如其他答案所建议。
所以我必须做以下事情(在React中):
window.getSelection()
答案 4 :(得分:0)
这是React中使用功能组件的示例:
const Post = () => {
const handleMouseUp() {
console.log(`Selected text: ${window.getSelection().toString()}`);
}
return (
<div onMouseUp={handleMouseUp}>Text</div>
);
}
Lyubomir指出window.getSelection()API可以解决问题!
答案 5 :(得分:0)
步骤1:-最初,您每次输入内容时,鼠标都会捕获每次
<textarea type="text"
className="contentarea__form__input"
onMouseUpCapture={this.selectedText}>
</textarea>
第2步:确保仅捕获您使用的if-else条件所选文本
selectedText = () => {
window.getSelection().toString() ? console.log(window.getSelection().toString()) : null;
}
答案 6 :(得分:0)
我刚刚为此做了一个自定义钩子(如果需要,在打字稿中):
export const useSelectedText = () => {
const [text, setText] = useState('')
const select = () => {
const selected = window.getSelection() as Selection
setText(selected.toString())
}
return [select, text] as const
}