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

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

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

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

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


当前回答

根据更新后的语法,你可以使用this.myRref.current.focus()

其他回答

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

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

应该是

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

关注坐骑

如果你只是想在一个元素挂载(初始渲染)时聚焦它,简单使用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} 
}

完整的演示

这是正确的方法,如何自动对焦。当你使用callback而不是string作为ref value时,它会被自动调用。你得到了你的ref,而不需要使用getDOMNode触摸DOM

render: function() {
  return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
  this._input.focus();
},

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

<input autoFocus name=...

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