2016-07-14 60 views
4

我在React中有一個textarea,我想變成一個「記事本」。這意味着我想讓「標籤」鍵縮進而不是沒有焦點。我看着this answer,但我無法使它與React一起工作。這裏是我的代碼:用React更改textarea中的光標位置

handleKeyDown(event) { 
    if (event.keyCode === 9) { // tab was pressed 
     event.preventDefault(); 
     var val = this.state.scriptString, 
      start = event.target.selectionStart, 
      end = event.target.selectionEnd; 

     this.setState({"scriptString": val.substring(0, start) + '\t' + val.substring(end)}); 
     // This line doesn't work. The caret position is always at the end of the line 
     this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1; 
    } 
} 
onScriptChange(event) { 
    this.setState({scriptString: event.target.value}); 
} 
render() { 
    return (
     <textarea rows="30" cols="100" 
        ref="input" 
        onKeyDown={this.handleKeyDown.bind(this)} 
        onChange={this.onScriptChange.bind(this)} 
        value={this.state.scriptString}/> 
    ) 
} 

當我運行此代碼,即使我按「tab」鍵在字符串中間,我的光標總是出現在字符串,而不是結束。任何人都知道如何正確設置光標位置?

回答

8

你必須改變光標位置狀態更新後(setState()不會立即發生變異this.state

爲了做到這一點,你必須包裝this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1;的功能,並將它傳遞的第二個參數setState(回調)。

handleKeyDown(event) { 
     if (event.keyCode === 9) { // tab was pressed 
      event.preventDefault(); 
      var val = this.state.scriptString, 
      start = event.target.selectionStart, 
      end = event.target.selectionEnd; 
      this.setState(
       { 
        "scriptString": val.substring(0, start) + '\t' + val.substring(end) 
       }, 
      () => { 
        this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1 
       }); 
     } 
} 

jsfiddle

+0

小提琴似乎打破 – Ezeewei

+1

我更新了它 – QoP

相關問題