Reactにおける入力フィールドの配列へのバインド
ステート notes に配列が格納されているとします:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
</div>;
}
また、配列要素の合計を求めるヘルパー関数もあるとします:
function getSum(arr) {
let sum = 0;
for (const elem of arr) {
sum += +elem;
}
return sum;
}
function App() {
...
}
ステートの配列に対してこのヘルパー関数を使用して、要素の合計を求め表示してみましょう:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
{getSum(notes)}
</div>;
}
では、3つの入力フィールドを作成し、各入力フィールドの value に配列の要素を1つずつ設定しましょう:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
<input value={notes[0]} />
<input value={notes[1]} />
<input value={notes[2]} />
{getSum(notes)}
</div>;
}
次に、入力フィールドに onChange イベントを追加します。その際、このイベントに対する共通のハンドラー関数を1つ作成します:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
// 共通のハンドラー関数
}
return <div>
<input value={notes[0]} onChange={event => changeHandler(0, event)} />
<input value={notes[1]} onChange={event => changeHandler(1, event)} />
<input value={notes[2]} onChange={event => changeHandler(2, event)} />
{getSum(notes)}
</div>;
}
ご覧の通り、関数 changeHandler は、第一引数として、その入力フィールドが編集する配列要素のインデックス番号を受け取ります。
この番号を使用して、配列の要素を入力フィールドの内容に置き換えることができます。
それでは、実装してみましょう:
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
これで、どの入力フィールドを編集しても、配列がリアクティブに変更され、それに応じて要素の合計が再計算されるようになります。
すべてのコードをまとめてみましょう:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
return <div>
<input value={notes[0]} onChange={event => changeHandler(0, event)} />
<input value={notes[1]} onChange={event => changeHandler(1, event)} />
<input value={notes[2]} onChange={event => changeHandler(2, event)} />
{getSum(notes)}
</div>;
}
入力フィールドをループで生成するようにすることもできます:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
const result = notes.map((note, index) => {
return <input
key={index}
value={note}
onChange={event => changeHandler(index, event)}
/>;
});
return <div>
{result}
{getSum(notes)}
</div>;
}
次の配列が与えられています:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
この配列の要素の算術平均を画面に表示してください。ループを使用して、要素を編集するための入力フィールドを作成してください。