ここでの私の目標は、フォームを作成することです。このフォームでは、リターンキーを押すと次の入力要素に移動し、最後の入力時にフォームを送信します。
これはモバイル向けに構築されており、ブラウザの「キーボードに移動」ボタンの代わりに「次へ」ボタンを使用するオプションがないため(これについて詳しくは、この回答を参照してください)。
コードも書いていますが、イベントを適切な場所でキャッチできないので、返品後すぐにフォームが送信されるか、イベントを防ぐと、ヒット後にフォーカスが変更されます。 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'));
あなたが最善のアプローチを使用しているとは思わない、説明させてください。入力のフォーカスはfocus
、ネイティブDOM要素のメソッドによって行われます。現在フォーカスしている入力に基づいてフォーカスする入力を知ることは、それらの入力のコンテナー(このApplication
場合はコンポーネント)に実装する必要があるロジックです。
私はあなたのコードにいくつかの重要な変更を加えました、そして今それは働いています:CodePen
説明させてください:
まず、フォームを防ぐためkeyPressed
に、キーが押されたときに入力のイベントの送信'Enter'
を防止していますsubmit
_onKeyPress(e) {
if (e.key === 'Enter') {
this.props.onSubmit(e);
e.preventDefault();
}
}
私たちは、いずれかの必要はありませんcomponenDidMount
たりcomponentDidUpdate
してTextInput
、すべての私達の必要性であるfocus
方法。
focus() {
this.textInput.focus();
}
ほとんどの変更はApplication
コンポーネントで行われます。まず第一に、状態は必要ありません。本当に必要なのは、入力を配列に入れて呼び出すことができるようfocus
にすることです。
constructor(props) {
super(props);
this.inputs = [];
}
フォーカスを変更するにfocus
は、TextInput
コンポーネントのメソッドを呼び出すための入力のインデックスが必要です。
_changeFocus(index) {
return e => {
this.inputs[index].focus();
};
}
その後、我々はへの入力を追加する方法を必要とするthis.inputs
、ref
私は方法を作成しました、プロパティが理想的である_addInput
。このためのヘルパーとして:
_addInput(index) {
return input => {
this.inputs[index] = input;
};
}
最後に、TextInput
sをレンダリングするときは、それぞれのインデックスを使用して、それら_addInput
をref
と_changeFocus
に渡す必要がありonSubmit
ます。
<TextInput ref={this._addInput(0)} onSubmit={this._changeFocus(1)} />
<TextInput ref={this._addInput(1)} onSubmit={this._changeFocus(0)} />
2番目TextInput
では、フォーカスを最初のフォーカスに変更しますが、フォームを送信する方が便利な場合があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加