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设置为国家的完整名称呢,它只有两个字母。
发布于 2021-06-25 12:32:42
当您设置选择选项的value属性时,它将选择具有相同值的匹配选项。
MenuItem值设置如下:
<MenuItem value={country.value}>{country.name}</MenuItem>值和country州实际上只接受国家缩写-但是一旦选择了匹配选项,元素的文本内容就是country.name,它给出了国家的全名。
https://stackoverflow.com/questions/68125427
复制相似问题