【问题标题】:How take name and id from a select如何从选择中获取名称和 ID
【发布时间】:2020-04-14 06:23:46
【问题描述】:

我使用反应钩子进行选择。目前只能取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-ui react-hooks


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 这可能是一种方法,但为此我必须将国家对象绑定到值: {country.country} 这是另一种方法,因为我只想绑定 id 而不是对象?
    • 您可以通过使用 array.filter 或 array.find 过滤您的国家/地区数组来设置 setCountry 并仅获取与所选 ID 匹配的国家/地区。但同样,最简单和最有效的解决方案是将县设置为值,因为这是您最终期望得到的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2022-06-15
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多