首页 > 解决方案 > 如何从选择中获取名称和 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。如何从选择中获取名称?

标签: material-uireact-hooks

解决方案


我猜 useState 中的默认值是错误的。您需要提供您所在国家/地区对象的形状。我假设你的国家对象看起来像

{
id:anumber,
countryName:"astring",
}

如果是这种情况,那么你应该做这样的事情

const [countries, setCountries] = useState([{id:0, countryName:""}]);
const [selectedCountry, setSelectedCountry] = useState({id:0, countryName:""});

推荐阅读