在组件渲染后,react如何设置聚焦在特定文本字段上?

文档似乎建议使用参考,例如:

在渲染函数的输入字段上设置ref="nameInput",然后调用:

this.refs.nameInput.getInputDOMNode().focus(); 

但是我该把它叫什么呢?我在几个地方试过了,但都不行。


当前回答

你可以在这里查看更新的版本

componentDidMount() {

    // Focus to the input as html5 autofocus
    this.inputRef.focus();

}
render() {
    return <input type="text" ref={(input) => { this.inputRef = input }} />
})

其他回答

重点关注功能组件使用createRef

给使用功能组件的开发人员。这似乎很合适。点击按钮后,焦点发生在inputfield上。我也附上了CodeSandbox链接。

import React from 'react';

export default function App() {
  const inputRef = React.createRef();
  return <>
    <input ref={inputRef} type={'text'} />
    <button onClick={() => {if (inputRef.current) { inputRef.current.focus() }}} >
      Click Here
    </button>
  </>
}

https://codesandbox.io/s/blazing-http-hfwp9t

自动对焦对我来说效果最好。我需要将一些文本更改为双击文本的输入,所以这是我最终得到的:

<input autoFocus onFocus={this.setCaretToEnd} value={this.state.editTodo.value} onDoubleClick={this.updateTodoItem} />

注意:要修复React在文本开头放置插入符号的问题,请使用以下方法:

setCaretToEnd(event) {
    var originalText = event.target.value;
    event.target.value = '';
    event.target.value = originalText;
}

在这里找到: https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js

您可以将该方法调用放在呈现函数中。或者在生命周期方法中,componentDidUpdate

从React 0.15开始,最简洁的方法是:

<input ref={input => input && input.focus()}/>

你应该在componentDidMount和refs回调中做。就像这样

componentDidMount(){
   this.nameInput.focus(); 
}

class App extends React.Component{ componentDidMount(){ this.nameInput.focus(); } render() { return( <div> <input defaultValue="Won't focus" /> <input ref={(input) => { this.nameInput = input; }} defaultValue="will focus" /> </div> ); } } ReactDOM.render(<App />, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script> <div id="app"></div>