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

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

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

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

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


当前回答

我也有同样的问题,但我也有一些动画,所以我的同事建议使用window.requestAnimationFrame

这是元素的ref属性:

ref={(input) => {input && window.requestAnimationFrame(()=>{input.focus()})}}

其他回答

你不需要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'));

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

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

更多信息

如果你只是想在React中自动对焦,这很简单。

<input autoFocus type="text" />

而如果你只是想知道把代码放在哪里,答案是componentDidMount()。

v014.3

componentDidMount() {
    this.refs.linkInput.focus()
}

在大多数情况下,您可以为DOM节点附加一个引用,而完全避免使用findDOMNode。

在这里阅读API文档:https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode

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

<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

阅读几乎所有的答案,但没有看到getRenderedComponent().props.input

设置文本输入参考

this.refs.username.getRenderedComponent () .props.input.onChange(”);