如何在 ReactJS 中获取突出显示的文本 (window.getSelection())

Red*_*ant 5 javascript ecmascript-6 reactjs

我一直在学习制作自定义 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'));
Run Code Online (Sandbox Code Playgroud)

函数的结果getSelectionText()根本不返回任何文本。如何在 ReactJS 中获取突出显示的文本?

cbr*_*ino 4

通过单击该按钮,您可以在触发事件之前取消选择文本。

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

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