gpt4 book ai didi

html - 我如何处理多个选择框以在单个状态下使用react

转载 作者:行者123 更新时间:2023-12-04 07:20:50 25 4
gpt4 key购买 nike

我的初始状态

const [state,setState] = useState({
country : "",
nationality : "",
})

我的第一个选择标签:

<select> //select for country
<option>Nepal<option/>
<option>USA<option/>
</select>

我的第二个选择标签:

<select> //select for nationality 
<option>Nepali<option/>
<option>Ameracain<option/>
</select>

最后,我需要单个状态下两个 select 标签的所有选定值。

const [state,setState] = useState({
country : "Nepal",
nationality : "Nepali",
})

最佳答案

here is a sample based on your example

import React, { useState } from "react";
import "./styles.css";

export default function App() {
const [state, setState] = useState({
country: "Nepal",
nationality: "Nepali"
});
const handleChange = (e) => {
const copy = { ...state };
switch (e.target.name) {
case "country":
copy.country = e.target.value;
break;
case "nationality":
copy.nationality = e.target.value;
break;
default:
break;
}
setState(copy);
};
return (
<div className="App">
<select name="country" onChange={handleChange}>
//select for country
<option>Nepal</option>
<option>USA</option>
</select>
My second select tag :
<select name="nationality" onChange={handleChange}>
//select for nationality
<option>Nepali</option>
<option>Ameracain</option>
</select>
{JSON.stringify(state)}
</div>
);
}

关于html - 我如何处理多个选择框以在单个状态下使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68515050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com