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

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

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

this.refs.nameInput.getInputDOMNode().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'));

其他回答

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

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

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

这不再是最好的答案。从v0.13开始,这个。在某些奇怪的情况下,refs可能在AFTER componentDidMount()运行之前不可用。

只需将autoFocus标签添加到输入字段,如上面的FakeRainBrigand所示。

如果你只是想在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

关注坐骑

如果你只是想在一个元素挂载(初始渲染)时聚焦它,简单使用autoFocus属性就可以了。

<input type="text" autoFocus />

动态焦点

要动态控制焦点,请使用通用函数对组件隐藏实现细节。

React 16.8 +功能组件- useFocus钩子

const FocusDemo = () => {

    const [inputRef, setInputFocus] = useFocus()

    return (
        <> 
            <button onClick={setInputFocus} >
               Focus
            </button>
            <input ref={inputRef} />
        </>
    )
    
}

const useFocus = () => {
    const htmlElRef = useRef(null)
    const setFocus = () => {htmlElRef.current &&  htmlElRef.current.focus()}

    return [ htmlElRef, setFocus ] 
}

完整的演示

React 16.3 +类组件-使用

class App extends Component {
  constructor(props){
    super(props)
    this.inputFocus = utilizeFocus()
  }

  render(){
    return (
      <> 
          <button onClick={this.inputFocus.setFocus}>
             Focus
          </button>
          <input ref={this.inputFocus.ref}/>
      </>
    )
  } 
}
const utilizeFocus = () => {
    const ref = React.createRef()
    const setFocus = () => {ref.current &&  ref.current.focus()}

    return {setFocus, ref} 
}

完整的演示

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();
        }
      }} />
    );
  },