如何在React中使用hooks在页面加载时聚焦特定组件?

8 浏览
0 Comments

如何在React中使用hooks在页面加载时聚焦特定组件?

在组件渲染后,设置特定文本字段的焦点有什么React方法?

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

在 render 函数中设置 ref=\"nameInput\",然后调用:

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

但我应该在哪里调用它呢?我已经尝试了几个地方,但无法使其工作。

admin 更改状态以发布 2023年5月22日
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