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

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

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

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

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


当前回答

<input type="text" autoFocus />

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

其他回答

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

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

重点关注功能组件使用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

React文档现在有一个专门的部分。https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

 render: function() {
  return (
    <TextInput
      ref={function(input) {
        if (input != null) {
          input.focus();
        }
      }} />
    );
  },

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

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

更多信息

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

应该是

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