【问题标题】:Set focus on a react-bootstrap.Input field using refs.x.getDOMNode.focus使用 refs.x.getDOMNode.focus 将焦点设置在 react-bootstrap.Input 字段上
【发布时间】:2015-02-28 13:38:06
【问题描述】:

JSX:

var Button = require("react-bootstrap").Button;
var Input = require("react-bootstrap").Input;
var MyClass = React.createClass({
        onclick: function () {
           this.refs.email.getDOMNode().focus();
           console.log('DOM element', this.refs.email.getDOMNode());
        }
        render: function () {
          return (
             <div>
                <Button onClick={this.onlick}>Login</Button>
                <Input ref='email' type='email' />
             </div>
            );
        },
    });  

注意事项:

  1. 输入字段是react-bootstrap.Input 类。
  2. getDOMNode().focus() 概念来自Facebook react docs

当按钮 onclick 处理程序运行时,电子邮件输入字段应该获得焦点,但它没有发生。我发现 react-bootstrap 输入字段类正在将真实的 DOM 输入字段呈现在包装 div 中。这是 console.log 的输出:

<div class="form-group" data-reactid=".1awy8d4e9kw.1.3.$=1$3:0.0.0.1.0">
  <input class="form-control" type="email" data-reactid=".1awy8d4e9kw.1.3.$=1$3:0.0.0.1.0.1:$input">
</div>

所以看起来输入没有获得焦点,因为焦点应用在包装 div 上,它拒绝它(我在控制台中使用document.activeElement 进行检查)。

问题是,如何关注真正的input元素?

注意: 有点无关,但 React 尊重 autoFocus 属性。这在渲染后需要立即设置焦点的情况下很有用。不过,它并不能替代程序化方式。

【问题讨论】:

    标签: reactjs react-jsx react-bootstrap


    【解决方案1】:

    尝试getInputDOMNode() 而不是getDOMNode()

    【讨论】:

    • 重要的是要注意,如果使用 React 0.13 你应该写 React.findDOMNode() 而在 React 0.14 之后你应该使用 ReactDOM.findDOMNode()
    【解决方案2】:

    在渲染中

    <FormControl
      type='text'
      ref={(c)=>this.formControlRef=c}
      />
    

    在事件处理程序中

    someHandler() {
      ReactDOM.findDOMNode(this.formControlRef).focus();
    }
    

    【讨论】:

      【解决方案3】:

      由于findDOMNode 不再是建议的方法并且可能被 Facebook 弃用,您应该使用 autoFocus 属性(由 React 框架提供,而不是 react-bootstrap)。这是 HTML autofocus 属性的跨浏览器 polyfill。

      <FormControl
        autoFocus
        ...
      />
      

      来源:

      1. Focusing to the FormControl
      2. Support needed for focusing inputs in modals?

      【讨论】:

        【解决方案4】:

        FormControl 提供inputRef 属性

        试试看,

        <FormControl inputRef={ref => { this.input = ref; }} />
        

        https://react-bootstrap.github.io/components/forms/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-06-03
          • 1970-01-01
          • 1970-01-01
          • 2021-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多