material-ui - 如何从选择中获取名称和 ID
问题描述
我使用反应钩子进行选择。到目前为止,我只能取id,但不能取名字。
选择代码:
const [countries, setCountries] = useState([]);
const [selectedCountry, setSelectedCountry] = useState(0);
useEffect(() => {
CountryGet().then(result => { setCountries(result); });
}, []);
const onChangeCountry = e => {
setSelectedCountry(e.target.value);
}
<FormControl className={classes.formControl}>
<InputLabel id="country_label">Country</InputLabel>
<Select id="country" value={selectedCountry} onChange={onChangeCountry}>
{countries.map((country) => (
<MenuItem key={country.id} value={country.id}>
{country.countryName}
</MenuItem>
))}
</Select>
</FormControl>
我希望在 selectCountry 中有 ID 和名称,但到目前为止我只得到 ID。如何从选择中获取名称?
解决方案
我猜 useState 中的默认值是错误的。您需要提供您所在国家/地区对象的形状。我假设你的国家对象看起来像
{
id:anumber,
countryName:"astring",
}
如果是这种情况,那么你应该做这样的事情
const [countries, setCountries] = useState([{id:0, countryName:""}]);
const [selectedCountry, setSelectedCountry] = useState({id:0, countryName:""});
推荐阅读
- android - Android ItemTouchHelper onChildDraw 让itemView回到原来的位置
- python - 元组对象不是可调用问题。(简单鳕鱼)
- python - Scrapy在身份验证后抓取每个链接
- mysql - 如何针对数组在表中搜索json编码的数组列并返回匹配结果?
- java - 基于字符偏移的动态重新定位的字符阅读器(如 FileReader)
- javascript - JavaScript 日期元素显示为第二天而不是当天
- excel - 将数据从 excel 复制到现有的 powerpoint 图表
- javascript - 使用 .select jquery 但没有得到任何选定的文本
- javascript - HTML5 直接从 Safari iOS 上的照片库中选择照片
- python - Python中的df_dict