在react的componentDidMount中触发input框的focus无效是为什么?

用react做的微信端页面,想达到的效果是在页面加载后input框自动获得焦点能够弹出移动端的键盘,所以在componentDidMount中触发input框的focus,但是无效是怎么回事?

componentDidMount: function () {
    var that = this;
    React.findDOMNode(this.refs.password).focus();    
}
阅读 13.1k
3 个回答

试试:

<input ... autoFocus={true} />

<input ... autoFocus  />

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }

  render() {
    return (
      <CustomTextInput
        ref={(input) => this.textInput = input} />
    );
  }
}

參考自: https://facebook.github.io/re...

React不是通过dom对象绑定函数的,而是在你的jsx代码里加入自动获取焦点的函数。

我直接把整段代码搬过来好了:)

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in an instance field (for example, this.textInput).
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />

        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

同意楼上的方法:https://reactjs.org/docs/refs...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题