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

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

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

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

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


当前回答

@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:

<input autoFocus name=...

注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。

其他回答

引用:@Dave对@Dhiraj的回答的评论;另一种方法是在被呈现的元素上使用ref属性的回调功能(在组件第一次呈现之后):

<input ref={ function(component){ React.findDOMNode(component).focus();} } />

更多信息

ReactDOMComponent:不要访问DOM节点的.getDOMNode();相反,直接使用节点。这个DOM节点由App渲染。

应该是

componentDidMount: function () {
  this.refs.nameInput.focus();
}

这一点对我很有用:

<input autoFocus={true} />
<input type="text" autoFocus />

总是先尝试简单和基本的解决方案,对我来说很有效。

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

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

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