Thuộc tính value của select từ mảng trong React
Giả sử các mục danh sách của chúng ta lại được lưu trữ trong một mảng:
function App() {
const texts = ['text1', 'text2', 'text3', 'text4'];
const [value, setValue] = useState('');
...
}
Hãy tạo các thẻ option bằng cách sử dụng mảng này,
thêm cho chúng các giá trị của phần tử mảng làm thuộc tính
value:
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>;
});
...
}
Sử dụng các thẻ đã tạo, chúng ta sẽ tạo một danh sách thả xuống:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
</div>;
Hãy hiển thị số thứ tự của mục được chọn trong một đoạn văn:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
lựa chọn của bạn: {value}
</p>
</div>;
Và bây giờ hãy hiển thị văn bản của mục được chọn, sử dụng số thứ tự của nó và mảng chứa các văn bản:
return <div>
<select value={value} onChange={event => setValue(event.target.value)}>
{options}
</select>
<p>
lựa chọn của bạn: {texts[value]}
</p>
</div>;
Tổng hợp tất cả lại, chúng ta có được mã sau:
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>
lựa chọn của bạn: {texts[value]}
</p>
</div>;
}