【问题标题】:ReactJS: How-to set focus to input-element when it enters the DOM?ReactJS:如何在输入元素进入 DOM 时设置焦点?
【发布时间】:2018-12-04 19:31:45
【问题描述】:

input 元素进入 DOM 时如何设置焦点?

场景

单击按钮时,会显示输入元素。如何设置焦点到这个元素?

代码片段

class Component extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      showInput: false
    }
  }

  render() {
      return (
        <div>
          <div onClick={() => {
              this.setState({showInput: true});
              ReactDOM.findDOMNode(this.refs.myInput).focus() // <- NOT WORKING
          }}>
            Show Input
          </div>
          {
            (this.state.showInput) ? (
                <input
                    type="text"
                    ref="myInput"
                />
            ) : ""
          }  
        </div>
      );
  }
}

在状态更改后调用ReactDOM.findDOMNode(this.refs.myInput).focus() 不起作用。同样在状态更改时仅更改 styletype 属性也不起作用。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    假设您一次只需要页面上的一个可见输入来自动对焦Poh Zi How's 建议使用autofocus 可能是最简单的。

    &lt;input type="text" autofocus/&gt;

    应该可以,不需要 JS!

    【讨论】:

    • 这太棒了!谢谢
    • 在 JSX 中,camelCase 属性:&lt;input type="text" autoFocus /&gt;
    【解决方案2】:

    componentDidMountcomponentDidUpdate 钩子中这样做:

    ReactDOM.findDOMNode(this.refs.myInput).focus()
    

    【讨论】:

    • 非常感谢您的成功!对于这种情况,componentDidUpdate 完成了工作!我添加了以下代码:componentDidUpdate() { if (ReactDOM.findDOMNode(this.refs.searchInput) !== null) { ReactDOM.findDOMNode(this.refs.searchInput).focus() } }
    • 一个很好的评论,不幸的是被删除了,还建议使用this.refs.myInput.focus()而不是findDOMNode。不过感谢您的评论!
    • 是的,不要使用已弃用的 ReactDom.findnode,它跳过了我的想法 this.refs.myInput.focus()
    • 或者实际上你可以在输入标签中使用autoFocus
    【解决方案3】:

    你应该使用参考

    <input ref={(input) => { this.inputSearch = input; }} defaultValue="search ... " />
    

    并使用此代码获得焦点

    this.inputSearch.focus();
    

    【讨论】:

      【解决方案4】:

      我必须将变量定义为HTMLInputElement 1st...

      private inputSearch: HTMLInputElement;
      

      然后将这个添加到控件中:

      ref={(input) => { this.inputSearch = input; }} 
      

      然后我可以构建/工作:

      this.inputSearch.focus();
      

      【讨论】:

        【解决方案5】:

        来自文档:

        "findDOMNode 仅适用于已挂载的组件(即已放置在 DOM 中的组件)。如果您尝试在尚未挂载的组件上调用此方法(如在 render() 上调用 findDOMNode()尚未创建的组件)将引发异常。”

        如 Piyush.kapoor 所述,您需要将其放入componentDidMount 和/或componentDidUpdate

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-27
          • 1970-01-01
          • 2018-12-30
          • 2012-06-18
          • 2020-05-15
          • 1970-01-01
          相关资源
          最近更新 更多