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

时间:2016-08-07 04:03:07

标签: javascript reactjs ecmascript-6

我一直在学习制作自定义降价编辑器。然而,我只是遇到了在使用降价包装之前获取突出显示的文本的问题。这是我的example

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'));

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

1 个答案:

答案 0 :(得分:2)

点击按钮,在触发事件之前取消选择文字。

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

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