reactjs 使用React将光标置于自动聚焦文本区域的开头

iyzzxitl  于 2023-01-08  发布在  React
关注(0)|答案(2)|浏览(252)

我正在使用一个文本区域,在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>
t3psigkw

t3psigkw1#

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

class App extends React.Component {

  handleFocus(e){
    const target = e.target;
    setTimeout(() => 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,因为使用鼠标聚焦时Chrome会出错

92vpleto

92vpleto2#

下面是答案,感谢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>

相关问题