React selektam value atribūti no masīva
Pieņemsim, ka mūsu saraksta vienumi atkal tiek glabāti massīvā:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
...
}
Veidosim ar šī masīva palīdzību
option tagus, pievienojot tiem kā atribūtus
value masīva elementu vērtības:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
const options = texts.map((text, index) => {
return <option key={index} value={index}>{text}</option>;
});
...
}
Izmantojot izveidotos tagus, izveidosim nolaižamo sarakstu:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
</div>;
Izvadīsim rindkopā izvēlētā vienuma numuru:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
jūsu izvēle: {value}
</p>
</div>;
Un tagad izvadīsim izvēlētā vienuma tekstu, izmantojot tā numuru un masīvu ar tekstiem:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
jūsu izvēle: {texts[value]}
</p>
</div>;
Apvienosim visu kopā un iegūsim šādu kodu:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
const options = texts.map((text, index) => {
return <option key={index} value={index}>{text}</option>;
});
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
jūsu izvēle: {texts[value]}
</p>
</div>;
}