ReactJS and autofocus

怎甘沉沦 提交于 2020-01-16 16:26:09

问题


I have a react-bootstrap modal with an <input>. I want to set the autofocus attribute on the <input>

The following works fine, but shows a warning in the console

<input type="text" autofocus='true' />
Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?

The following options do not work, in the sense that they do not focus the input when opening the modal:

<input type="text" autoFocus='true' />
<input type="text" autoFocus={true} />
<input type="text" autoFocus />

What is the recommended way of setting autofocus. Or how should I mute the warnings for the example that works well?

Note: This is react 16.8.6


回答1:


Refs is what you want,

constructor(props) {
    super(props);
    this.myRef = React.createRef();
}

componentDidMount(){
  this.myRef.current.focus();
}

<input type="text"  ref={this.myRef} />


来源:https://stackoverflow.com/questions/56896201/reactjs-and-autofocus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!