我正在使用带有 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/