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

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

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

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

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


当前回答

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

其他回答

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

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

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

这一点对我很有用:

<input autoFocus={true} />

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

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

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

React 16.3增加了一个新的方便的方法来处理这个问题,在组件的构造函数中创建一个ref,并像下面这样使用它:

class MyForm extends Component {
  constructor(props) {
      super(props);

      this.textInput = React.createRef();
  }

  componentDidMount() {
    this.textInput.current.focus();
  }

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

有关React的更多细节。createRef,你可以在React博客中查看这篇文章。

更新:

从React 16.8开始,可以在函数组件中使用useRef钩子来实现相同的结果:

import React, { useEffect, useRef } from 'react';

const MyForm = () => {
  const textInput = useRef(null);

  useEffect(() => {
    textInput.current.focus();
  }, []);

  return (
    <div>
      <input ref={textInput} />
    </div>
  );
};