Как сделать автофокус input-у в react.js?

К сожаление react в не поддерживает атрибут в форме autofocus.
Вроде .focus() позволяет сделать автофокус, но как прикрутить, что-то не могу сообразить.
Какие есть варианты решения для автофокуса определённому input-у?
  • Вопрос задан
  • 17463 просмотра
Пригласить эксперта
Ответы на вопрос 3
xoma2
@xoma2
Программист
Я делал вот так

autoFocus={true}

Все работает 100%. Если надо сделать автофокус после текста который есть в input делаю вот так.

componentDidMount() {
		this.refs.searchInput.value = this.refs.searchInput.value
	},
		<input type="text"
			   ref="searchInput"
			   autoFocus={true}
			   value={this.props.searchTerm}
                > </input>
Ответ написан
Комментировать
liubko
@liubko
в react v13 еще можно так:

https://facebook.github.io/react/docs/more-about-r...


The ref Callback Attribute
The ref attribute can be a callback function instead of a name. This callback will be executed immediately after the component is mounted. The referenced component will be passed in as a parameter, and the callback function may use the component immediately, or save the reference for future use (or both).

It's as simple as assigning a ref attribute to anything returned from render such as:
<input ref={ function(component){ React.findDOMNode(component).focus();} } />




или так
React.findDOMNode(this.refs.myTextInput).focus();
Ответ написан
Комментировать
maxfarseer
@maxfarseer
https://maxpfrontend.ru, обучаю реакту и компании
Подробно описано здесь
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы