简体   繁体   English

reactjs环境下document.getSelection是如何工作的?

[英]How does document.getSelection work under reactjs environment?

I was working on a electron-react project for epub file.我正在为epub文件开发一个电子反应项目。 Right now, I am planning to make the app capable of selecting text field and highlight it.现在,我计划让应用程序能够选择文本字段并突出显示它。

To achieve it, I was trying to use web's Window.getSelection api .为了实现它,我试图使用 web 的Window.getSelection api However, there are some really weird things come up like in this .然而,在这种情况下会出现一些非常奇怪的事情。

In short, I am unable to capture the Selection object.简而言之,我无法捕获 Selection 对象。 It seems like even if I log the Selection object, this object could somehow jump to something else.似乎即使我记录了 Selection 对象,这个对象也可能以某种方式跳转到其他东西。 Also, I cannot even serialize the Selection object with JSON.stringfy .此外,我什至无法使用JSON.stringfy序列化 Selection 对象。 This is super surprising, and this is my first time seeing something like this (I will get empty object to stringfy the Selection object).这太令人惊讶了,这是我第一次看到这样的东西(我会得到空对象来字符串化 Selection 对象)。

So how to use Window.getSelection properly under react-electron environment?那么如何在 react-electron 环境下正确使用Window.getSelection呢? Or this api will not work well for text content which is generated by react's dangerouslySetInnerHTML?或者这个 api 不适用于由 react 的危险的SetInnerHTML 生成的文本内容?

Looks like the window.getSelection api needs to toString the selected object.看起来window.getSelection api 需要toString所选对象。

const getSelectionHandler = () => {
  const selection = window.getSelection();
  console.log("Got selection", selection.toString());
};

Super simple textarea and button to get selection react demo超级简单的textarea和按钮来获取选择反应演示

编辑relaxed-germain-rpo7e

this solution might help someone, catch last selection这个解决方案可能会帮助某人,抓住最后的选择

const selection = useRef('');
        
const handleSelection = () => {
  const text = document.getSelection().toString();
  if (text) {
    selection.current = text;
  }
 }
    
 useEffect(() => {
   document.addEventListener('selectionchange', handleSelection);
   return () => {
     document.removeEventListener('selectionchange', handleSelection);
   };
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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