ReactJS:当输入元素进入 DOM 时如何将焦点设置到输入元素?

2024-02-27

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

Scenario

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

代码片段

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>
      );
  }
}

Calling ReactDOM.findDOMNode(this.refs.myInput).focus()状态改变后不起作用。也只是改变style or type状态更改时的属性不起作用。


假设您一次只需要页面上的一个可见输入即可实现自动对焦婆子怎么样 https://stackoverflow.com/users/6150999/poh-zi-how建议使用autofocus可能是最简单的。

<input type="text" autofocus/>

应该可以解决问题,不需要 JS!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ReactJS:当输入元素进入 DOM 时如何将焦点设置到输入元素? 的相关文章

随机推荐