Моя цель здесь - создать форму, которая переводит вас к следующему элементу ввода, когда вы нажимаете клавишу возврата, и отправляет форму, когда вы находитесь на последнем вводе.
Это создается для мобильных устройств, и поскольку нет возможности использовать кнопку «Далее» вместо кнопки «Перейти к клавиатуре» в браузере (дополнительную информацию об этом см. этот ответ).
Чтобы лучше это представить, вот картинка:
Я также написал некоторый код, но дело в том, что я не могу поймать событие в нужном месте, поэтому форма сразу же отправляется после возврата или когда я предотвращаю событие, фокус меняется после того, как я нажимаю вернуться 2 раза.
См. пример здесь: https://codepen.io/ofhouse/pen/Rgwzxy (I также вставил код ниже)
class TextInput extends React.Component {
constructor(props) {
super(props);
this._onKeyPress = this._onKeyPress.bind(this);
}
componentDidMount() {
if (this.props.focus) {
this.textInput.focus();
}
}
componentDidUpdate(nextProps) {
if (nextProps.focus) {
this.textInput.focus();
}
}
_onKeyPress(e) {
if (e.key === 'Enter') {
this.props.onSubmit(e);
}
}
render() {
return (
<div>
<input
type="text"
onKeyPress={this._onKeyPress}
ref={input => {
this.textInput = input;
}}
/>
</div>
);
}
}
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
currentElement: 0,
};
}
_submitForm(e) {
// If I remove this preventDefault it works, but also the form is submitted --> SiteReload
e.preventDefault();
}
_changeFocus(nextElement) {
return e => {
this.setState({
currentElement: nextElement,
});
};
}
render() {
const { currentElement } = this.state;
return (
<form>
<h1>React input focus</h1>
<TextInput focus={currentElement === 0} onSubmit={this._changeFocus(1)} />
<TextInput focus={currentElement === 1} onSubmit={this._changeFocus(0)} />
<div>
<button type="submit" onClick={this._submitForm}>Submit</button>
</div>
</form>
);
}
}
ReactDOM.render(<Application />, document.getElementById('app'));