簡體   English   中英

如何在 ReactJs 中根據所選國家創建城市下拉列表

[英]How To Create Cities Dropdown Based on Selected Country In ReactJs

我有一個具有以下結構的 countryList 數組:

    export const countryList = [ 
    {name: 'Singapore', code: 'SG', cities:[
        
            "Ang Mo Kio New Town",
            "Ayer Raja New Town",
            "Bedok New Town",
            "Boon Lay",
            "Bukit Batok New Town",
            "Bukit Panjang New Town",
            "Bukit Timah",
            "Bukit Timah Estate",
            "Changi Village",
            "Choa Chu Kang New Town",
            "Clementi New Town",
            "Holland Village",
            "Hougang",
            "Jurong East New Town",
            "Jurong Town",
            "Jurong West New Town",
            "Kalang",
            "Kampong Pasir Ris",
            "Kembangan",
            "Pandan Valley",
            "Pasir Panjang",
            "Punggol",
            "Queenstown Estate",
            "Serangoon",
            "Simei New Town",
            "Singapore",
            "Tai Seng",
            "Tampines New Town",
            "Tanglin Halt",
            "Tanjong Pagar",
            "Toa Payoh New Town",
            "Woodlands New Town",
            "Yew Tee",
            "Yishun New Town"
    ]}, 
        {name: 'Bahrain', code: 'BH',cities:[
            "Al Budayyi`",
            "Al Hadd",
            "Al Hamalah",
            "Al Janabiyah",
            "Al Markh",
            "Al Muharraq",
            "Bani Jamrah",
            "Barbar",
            "Jurdab",
            "Madinat `Isa",
            "Madinat Hamad",
            "Manama",
            "Oil City",
            "Sanabis",
            "Sanad",
            "Sitrah",
            "Tubli"
          ],}, 
    ];

我有一個世界上所有國家的下拉列表,現在我想要當用戶選擇一個特定國家時,例如新加坡,它只會填充新加坡的可用城市

這是我到目前為止所嘗試的:

    const [fromCountires, setFromCountries] = useState("");
    const [fromCity, setFromCity] = useState();

    const handleFromCountries = e => {
        const country = countryList.find(
            country => country.name === e.target.value
        );
        const cities = country.cities?.find(city => city.cities === country);

        setFromCountries(country.name);
        setFromCity(cities.cities);
        setFromCountriesCode(country.code);
    };

    useEffect(() => {
        console.log(fromCountires);
        console.log(fromCountriesCode);
    }, [fromCountires, fromCountriesCode]);

    return (
        <>
            //this is the drop down that shows all the countries
            <Form.Select
                aria-label="Select Country"
                onChange={e => handleFromCountries(e)}
            >
                <option></option>
                {countryList.map((country, key) => (
                    <option key={key} title={country.code} value={country.name}>
                        {country.name}
                    </option>
                ))}
            </Form.Select>
            //this is the drop down that i want the cities to populate inside
            for the selected country only. but it isn't working as expected and
            is throwing errors.
            <Form.Label className={"fw-bold"}>City</Form.Label>
            <Form.Select
                aria-label="Select City"
                onChange={e => handleFromCountries(e)}
            >
                <option></option>
                {fromCity.map((city, key) => (
                    <option key={key} title="" value={city.cities}>
                        {city.cities}
                    </option>
                ))}
            </Form.Select>
        </>
    );

如何使用我擁有的數據結構來實現這一點?

您嘗試設置所選城市的方式存在一些問題。

  1. fromCity (formCities) state 應初始化為空數組。
  2. setFromCity(cities.cities)應該是setFromCity(country.cities)
  3. {city.cities}應該是{city}

嘗試如下。


function App() {
  const [fromCountires, setFromCountries] = useState("");
  const [fromCities, setFromCities] = useState([]);

  const handleFromCountries = (e) => {
    const country = countryList.find(
      (country) => country.name === e.target.value
    );
    setFromCountries(country.name);
    setFromCities(country.cities);
  };

  return (
    <Form.Group controlId="custom-select">
      <Form.Label>Select Country</Form.Label>
      <Form.Control
        as="select"
        className="rounded-0 shadow"
        onChange={(e) => handleFromCountries(e)}
      >
        <option className="d-none" value="">
          Select Country
        </option>
        {countryList.map((country, key) => (
          <option key={key} title={country.code} value={country.name}>
            {country.name}
          </option>
        ))}
      </Form.Control>
      <Form.Label>Select City</Form.Label>
      <Form.Control as="select" className="rounded-0 shadow">
        <option className="d-none" value="">
          Select City
        </option>
        {fromCities.map((city, key) => (
          <option key={key} title="" value={city}>
            {city}
          </option>
        ))}
      </Form.Control>
    </Form.Group>
  );
}

export default App;

代碼沙箱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM