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

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

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

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

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


当前回答

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

其他回答

你应该在componentDidMount和refs回调中做。就像这样

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>

从React 0.15开始,最简洁的方法是:

<input ref={input => input && input.focus()}/>

我也有同样的问题,但我也有一些动画,所以我的同事建议使用window.requestAnimationFrame

这是元素的ref属性:

ref={(input) => {input && window.requestAnimationFrame(()=>{input.focus()})}}

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

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