使用React在自动对焦的textarea开头的光标

问题描述 投票:1回答:2

我正在使用带有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>
javascript html reactjs
2个回答
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,因为当使用鼠标聚焦时,铬会变得混乱


0
投票

这是答案,感谢Gabriele Petrioli:

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>
© www.soinside.com 2019 - 2024. All rights reserved.