ReactJS中如何获取高亮文本(window.getSelection())

5

我一直在学习制作自定义的Markdown编辑器。然而,我遇到了一个问题,在将文本用Markdown语法包裹之前,如何获取高亮文本。以下是我的示例

class TextArea extends React.Component {
    constructor(props){
    super(props);
    this.state = {
        comment:'He oppose at thrown desire of no. Announcing impression unaffected day his are unreserved indulgence.She oppose at thrown desire of no..'
    };
    this.onClickMakeBold = this.onClickMakeBold.bind(this);
  }

  render(){
    return <div>
       <button onClick={this.onClickMakeBold}>Bold</button> 
         <div>
           <textarea ref="textarea">{this.state.comment}</textarea>
        </div>
    </div>
  }

  onClickMakeBold(){
    console.log(getSelectionText()) 
  }
}
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control"){
        text = document.selection.createRange().text;
    }else{
            alert('no')
    }
    return text;
}

React.render(<TextArea />, document.getElementById('container'));
< p > getSelectionText() 函数的结果没有返回任何文本。我该如何在 ReactJS 中获取高亮文本?< /p >

你应该尝试一下DraftJS,这是Facebook推出的超酷编辑器。 - vijayst
2个回答

4

点击按钮时,在事件触发之前取消选定的文本

将回调传递给您的按钮,作为onMouseDown,因为此事件发生在标准点击副作用之前。

另外:如果您希望在处理事件后保留所选文本,请在回调函数中使用event.preventDefault()


嗨,感谢你的答案,但是我无法在这段代码中使用event.preventDefault()。document.onmouseup对我来说也没有返回任何结果。 让我们看一下这段代码: let doit = () => { document.onmouseup = () => { let a2 = window.getSelection().toString(); console.log(a2); return a2; // a2是空的 }; }; - Farbod Aprin

1

这里提供一个纯粹使用React Hook的解决方案,无需任何库!

如果需要克隆小包或有任何问题,请访问: https://github.com/Farbod29/React-text-highlighter-with-hook-

import React, { useState, useEffect } from 'react';
import './highlight.css';

export default function Highlighter() {
  const [highlightedText, setHighlightedText] = useState(
    'highlighted text will be shown here!'
  );
  useEffect(() => {
    const saveSelection = () => {
      setHighlightedText(window.getSelection().toString());
    };
    document.addEventListener('mouseup', saveSelection);
    return () => document.removeEventListener('mouseup', saveSelection);
  }, []);
  return (
    <>
      <section className="card">
        <div>
          <div className="margin-top-zero txt">
            Here is react text highlighter with hook and use state/Effect, 
            understand if you have any question just email or add issue in above git ripo!
         
          </div>
          {/* {ghasem} */}
          <div className="txt">{highlightedText}</div>
          <div // parent of button
          >
            <button className="btn"> Add Highlighted text </button>
          </div>
        </div>
      </section>
    </>
  );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接