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

标签 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>

最佳答案

您可以使用 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 在用鼠标聚焦时会搞砸

关于javascript - 使用 React 将光标置于自动聚焦文本区域的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486424/

相关文章:

reactjs - React 中的响应式背景图像

javascript - JavaScript 中的 IndexOf 方法是否比遍历数组更有效?

javascript - Jquery 可排序 : clone + appendTo more than one possible target

javascript - PHP 在单选按钮上将单选值发布到下一页

html - 填充 float 的左侧 : right element in a full width design

javascript - 使用 React 中的下拉菜单过滤来自 API 的数据

javascript - 如何在同一页面进行登录和注销?

html - css 边框会完全改变 div 大小吗?

javascript - 存储 "javascript' s 数据的 HTML 标签”?

reactjs - 如何测试异步/等待 API 调用和更新 React 状态