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

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

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

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

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


当前回答

最简单的答案是在输入文本元素中添加ref="some name"并调用下面的函数。

componentDidMount(){
   this.refs.field_name.focus();
}
// here field_name is ref name.

<input type="text" ref="field_name" />

其他回答

你不需要getInputDOMNode??在这种情况下……

当组件被挂载时,只需简单地获取ref和focus()它——componentDidMount…

import React from 'react';
import { render } from 'react-dom';

class myApp extends React.Component {

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

  render() {
    return(
      <div>
        <input ref={input => { this.nameInput = input; }} />
      </div>
    );
  }

}

ReactDOM.render(<myApp />, document.getElementById('root'));

根据更新后的语法,你可以使用this.myRref.current.focus()

这是正确的方法,如何自动对焦。当你使用callback而不是string作为ref value时,它会被自动调用。你得到了你的ref,而不需要使用getDOMNode触摸DOM

render: function() {
  return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
  this._input.focus();
},

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

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

这一点对我很有用:

<input autoFocus={true} />