如何在渲染后将焦点设置在输入字段上?

23 浏览
0 Comments

如何在渲染后将焦点设置在输入字段上?

在组件呈现后,设置特定文本字段焦点的 react 方法是什么?

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

在 render 函数中设置 ref =“nameInput” 在我的输入字段上,然后调用:

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

但我应该在哪里调用它?我尝试了几个地方,但是我无法让它工作。

admin 更改状态以发布 2023年5月21日
0
0 Comments

你应该在 componentDidMountrefs 回调函数 中去做。类似这样:

componentDidMount(){
   this.nameInput.focus(); 
}

class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
  render() {
    return(
        
         { this.nameInput = input; }} 
          defaultValue="will focus"
        />
    );
  }
}
ReactDOM.render(, document.getElementById('app'));




0
0 Comments

@Dhiraj的答案是正确的,为方便起见,当输入框被挂载时,您可以使用autoFocus属性使输入框自动聚焦:


请注意,在jsx中,它是autoFocus(大写F),而不是在不区分大小写的普通html中。

0