Legarea input-urilor la un array în React
Să presupunem că în starea notes este stocat un array:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
</div>;
}
Să presupunem că avem și o funcție helper, care calculează suma elementelor array-ului:
function getSum(arr) {
let sum = 0;
for (const elem of arr) {
sum += +elem;
}
return sum;
}
function App() {
...
}
Să calculăm și să afișăm suma elementelor array-ului nostru din stare, folosind funcția noastră helper:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
{getSum(notes)}
</div>;
}
Acum să facem trei input-uri și în value
fiecărui input să scriem unul dintre elementele array-ului:
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>;
}
Acum să adăugăm evenimentul onChange
input-urilor noastre. În același timp, să facem o singură funcție
de gestionare a acestui eveniment:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
// funcția comună de gestionare
}
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>;
}
După cum vedeți, funcția changeHandler
primește ca prim parametru numărul elementului
array-ului pe care îl editează acest input.
După acest număr, putem înlocui elementul array-ului cu conținutul input-ului.
Să facem asta:
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
Acum putem edita orice input, în timp ce array-ul se va modifica reactiv și, în consecință, suma elementelor sale se va recalcula.
Să adunăm tot codul nostru împreună:
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>;
}
Se poate face astfel încât input-urile să fie formate într-o buclă:
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>;
}
Este dat următorul array:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Afișați pe ecran media aritmetică a elementelor acestui array. Într-o buclă faceți input-uri pentru editarea elementelor.