【发布时间】:2021-08-22 19:11:00
【问题描述】:
我是 React 的菜鸟,我想填写 <select>
我遇到的问题是当我想点击我的一项时...下拉仅在我将我的项目进行编码时显示不同的选项。这是我的代码
父组件
import React, { Fragment, useState, useEffect } from "react";
import Country from "./Country";
const CountriesList = ({ handleOnChange }) => {
const [countriesLoaded, setCountriesLoaded] = useState(false);
const [countriesList, setCountriesList] = useState([]);
const getCountries = async () => {
const api = "https://restcountries.eu/rest/v2/all";
const response = await fetch(api);
const countrieslst = await response.json();
setCountriesList(countrieslst);
setCountriesLoaded(true);
};
useEffect(() => {
getCountries();
}, [countriesList]);
return (
<Fragment>
<select id="country" name="country" onChange={handleOnChange}>
<option value="">-- Select a country --</option>
{countriesLoaded
? countriesList.map((country) => (
<Country key={country.alpha2Code} countryItem={country} />
))
: null}
</select>
</Fragment>
);
};
export default CountriesList;
子组件
import React from "react";
const Country = ({ country }) => {
return <option value={country.alpha2Code}>{country.name}</option>;
};
export default Country;
如果我检查 DOM 没问题,但只显示我的第一个选项
Thnx 4 支持,祝你有美好的一天!
【问题讨论】:
-
那么当你点击下拉菜单时会发生什么?打不开?你能分享一个代码沙盒链接吗?