渲染后将焦点设置在输入上 [英] Set focus on input after render

查看:128
本文介绍了渲染后将焦点设置在输入上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在呈现组件后,将焦点设置在特定文本字段上的反应方式是什么?

What's the react way of setting focus on a particular text field after the component is rendered?

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

Documentation seems to suggest using refs, e.g:

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

Set ref="nameInput" on my input field in the render function, and then call:

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

但我应该在哪里打个电话?我已经尝试了几个地方,但我无法让它工作。

But where should I call this? I've tried a few places but I cannot get it to work.

推荐答案

你应该在 componentDidMount 和 改为回拨 。这样的东西

You should do it in componentDidMount and refs callback instead. Something like this

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

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>

这篇关于渲染后将焦点设置在输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆