首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Hooks很奇怪

React Hooks很奇怪
EN

Stack Overflow用户
提问于 2021-06-25 12:25:58
回答 1查看 44关注 0票数 0
代码语言:javascript
复制
import './App.css';
import { MenuItem, FormControl, Select, Card, CardContent } from "@material-ui/core";

function App() {
  const [countries, setCountries] = useState([]);
  const [country, setCountry] =useState("WorldWide");

  useEffect(() => {
    const getCountriesData = async () => {
      await fetch("https://disease.sh/v3/covid-19/countries").then(response => response.json()).then(data => {
        const countries = data.map(country => ({
          name: country.country,
          value: country.countryInfo.iso2
        }));
        setCountries(countries);
      });
    };
    getCountriesData();
  }, []);

  const onCountryChange = (event) => {
    const countryCode = event.target.value;
    setCountry(countryCode);
  }

  return (
    <div className="app">
      <div className="app__header">
        <h1>Covid-19 Tracker</h1>
        <FormControl className="app__dropdown">
          <Select
            variant="outlined"
            onChange={onCountryChange}
            value={country}
          >
            <MenuItem value="WorldWide">WorldWide</MenuItem>
            {countries.map(country => (<MenuItem value={country.value}>{country.name}</MenuItem>))}

          </Select>

        </FormControl>
      </div>
      {/* Title + Select input dropdown */}

      {/* InfoBoxes */}
      {/* InfoBoxes */}
      {/* InfoBoxes */}

      {/* Table */}
      {/* Graph */}
      {/* Map */}
    </div>
  );
}

export default App;

在上面的代码中,我使用了一个状态country,它是通过setCountry更新的,具体取决于用户从选择下拉选项中选择什么。我正在学习一个教程,但我不明白的是,在函数onCountryChange()中,当我执行setCountry(countryCode)时,所选国家的名称会显示出来。每件事都能正常工作,但如何工作呢?因为countryCode设置为event.target.value,而value只是特定国家的两个字符代码。那么,当我传递的只是国家代码时,setCountry如何将country设置为国家的完整名称呢,它只有两个字母。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-25 12:32:42

当您设置选择选项的value属性时,它将选择具有相同值的匹配选项。

MenuItem值设置如下:

代码语言:javascript
复制
<MenuItem value={country.value}>{country.name}</MenuItem>

值和country州实际上只接受国家缩写-但是一旦选择了匹配选项,元素的文本内容就是country.name,它给出了国家的全名。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68125427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档