這裏我的目標是創建一個表單,當你點擊返回鍵並在最後一次輸入時提交表單時,該表單會將你選擇到下一個輸入元素。用反應改變文本輸入的焦點
這是爲移動設備構建的,因爲在瀏覽器中沒有使用「下一步」按鈕而不是「轉到鍵盤」按鈕的選項(關於此的更多信息,請參閱this answer)。
我也寫了一些代碼,但這裏的關鍵是,我沒能趕上在正確的位置的情況下,這樣的形式得到在返回後立即提交或者當我阻止事件發生時,在我返回2次後焦點發生改變。
看到這裏的例子:https://codepen.io/ofhouse/pen/Rgwzxy(我也粘貼下面的代碼)
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'));
哇,非常感謝你花時間詳細指出了一切!你的方法比我的更清潔,在這裏真正學到了一些東西。我已經在我的代碼上進行了測試,它運行得非常好,肯定爲我節省了幾個小時。謝謝! – ofhouse