使用React在自动聚焦的文本区域开始时使用光标

时间:2018-11-26 17:43:48

标签: javascript html reactjs

我正在使用一个带有React自动安装焦点的文本区域,以便将光标放在文本区域的最末端。如何将光标放置在最开始的位置(请参见下面的代码段)?谢谢!

class App extends React.Component {
  componentDidMount() {
    this.textArea.focus();
  }
  
  render() {
    return (
      <textarea 
        ref={node => this.textArea = node}
        value="Hello, I want this cursor to be at the beginning (before the hello) when on focus, and not at the end."
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

2 个答案:

答案 0 :(得分:2)

您可以使用HTMLTextAreaElement.selectionEnd属性,并在焦点事件触发时将其设置为0。

class App extends React.Component {

  handleFocus(e){
    const target = e.target;
    setTimeout(()=>e.target.selectionEnd = 0,0);
  }
  
  render() {
    return (
      <textarea 
        onFocus={this.handleFocus} 
        value="Hello, I want this cursor to be at the beginning (before the hello) when on focus, and not at the end."
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>


更新了答案并添加了setTimeout,因为用鼠标聚焦时铬会弄乱

答案 1 :(得分:0)

这是答案,这要感谢加布里埃莱·彼得里奥利:

class App extends React.Component {
  componentDidMount() {
    this.textArea.selectionEnd=0;
    this.textArea.focus();
  }
  
  render() {
    return (
      <textarea 
        ref={node => this.textArea = node}
        value="Hello, I want this cursor to be at the beginning (before the hello) when on focus, and not at the end."
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>