【发布时间】:2022-01-11 13:03:41
【问题描述】:
我有一组选择菜单,当我使用 onChange={updateValue} 事件选择一个选项时,我试图更改一个值。当我第一次选择一个选项时,选择菜单中的值没有更新。 它只会在我第二次尝试选择一个选项时发生变化。不知道我做错了什么。
编辑:我做了更多研究 (OnChange event using React JS for drop down),我相信我也需要使用 setState 更新选择的值。如果没有每个值的变量并再次设置状态,我无法弄清楚如何做到这一点。
let selectMenus = [
{
id: 'id1',
name: 'name1',
label: 'label1',
value: '0',
options: [
{
text: 'All ages',
value: '0',
},
{
text: '35 - 37 yrs',
value: '1',
},
],
buttonLabel: 'Refresh',
},
{
id: 'id2',
name: 'name2',
label: 'label2',
value: '1',
options: [
{
text: 'All ages',
value: '0',
},
{
text: '45 - 50 yrs',
value: '1',
},
],
buttonLabel: 'Refresh',
},
];
const [url, setUrl] = useState('http://localhost:5000/selectDropdowns1');
const updateValue = () => {
setUrl('http://localhost:5000/selectDropdowns2');
};
<form>
{selectMenus.map((select) => (
<div key={select.id} className='select-container'>
<label htmlFor={select.id}>{select.label}</label>
<select id={select.id} name={select.name} value={select.value} onChange={updateValue}>
{select.options.map((option) => (
<option value={option.value} key={uuid()}>
{option.text}
</option>
))}
</select>
<button>{select.buttonLabel}</button>
</div>
))}
</form>;
【问题讨论】:
标签: javascript reactjs select onchange setstate