2016-08-07 3 views
1

私はカスタムマークダウンエディタを作ることを学んでいます。しかし、私はマークダウンでそれをラップする前に強調表示されたテキストを取得するという問題に直面しました。ここでは、すべての任意のテキストを返さないgetSelectionText()機能からの私exampleReactJSでハイライトされたテキスト(window.getSelection())を得るには

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

結果です。 ReactJSでどのように強調表示されたテキストを取得できますか?

+0

Facebookからの超クールなエディタDraftJSを試してみてください。 – vijayst

答えて

1

ボタンをクリックすると、のテキストの選択が解除され、の前にイベントが発生します。

ボタンへのコールバックをonMouseDownとして渡します。このイベントは、標準的なクリックの副作用が発生する前に発生します。

また、イベント処理後にテキストを選択したままにしたい場合は、コールバック関数でevent.preventDefault()を使用してください。

関連する問題