gpt4 book ai didi

reactjs - 使用 React Hooks 的级联下拉

转载 作者:行者123 更新时间:2023-12-05 00:55:28 26 4
gpt4 key购买 nike

大家好,我是 React 新手。我正在尝试使用 react 钩子(Hook)创建一个级联下拉列表,我做的方式很好,但我觉得我做的方式有问题。请检查此代码并告诉我有一种方法可以改进我的代码。在此先感谢

import React, { useState } from 'react';
import './App.css';


function App() {

const[data, setName] = useState({
countrie:"",
state:""
});


let state;
const countrie =['Germany','India','France']

const gstate = ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn']
const istate = ['Delhi', 'Kolkata', 'Mumbai', 'Bangalore']
const fstate =['Auvergne','Bretagne','Corse','Centre']

if(data.countrie==="Germany"){

state = gstate.map((gstate,key)=> <option key={key} value={gstate}>{gstate}</option>)

}else if(data.countrie==="India"){

state = istate.map((istate,key)=> <option key={key} value={istate}>{istate}</option>)

}else{

state = fstate.map((fstate,key)=> <option key={key} value={fstate}>{fstate}</option>)
}

const countries = countrie.map((countrie,key)=> <option key={key} value={countrie}>{countrie}</option>)


function handleCountry(e){

setName({...data,countrie:e.target.value});

}

function handleStateChange(e){

setName({...data,state:e.target.value});
}

return (
<form onSubmit={handleSubmit}>
<div>
<select value={data.countrie} onChange={handleCountry}>
{countries}
</select>
</div>

<div>
<select value={data.state} onChange={handleStateChange}>
{state}
</select>
</div>
<input type="submit" />
</form>
);
}

export default App;

最佳答案

我的最佳建议是更改结合国家和州的数据结构。这样做可以更容易地映射每个国家并获得州,而无需映射变量。这也使其更具可扩展性。

以下是使用国家数据作为集合的示例:

Codesandbox

import React, { useState } from "react";

const countriesData = [
{
name: "Germany",
states: ["Duesseldorf", "Leinfelden-Echterdingen", "Eschborn"]
},
{
name: "India",
states: ["Delhi", "Kolkata", "Mumbai", "Bangalore"]
},
{
name: "France",
states: ["Auvergne", "Bretagne", "Corse", "Centre"]
}
];

function Form() {
const [{ country, state }, setData] = useState({
country: "Germany",
state: ""
});

const countries = countriesData.map((country) => (
<option key={country.name} value={country.name}>
{country.name}
</option>
));

const states = countriesData.find(item => item.name === country)?.states.map((state) => (
<option key={state} value={state}>
{state}
</option>
));

function handleCountryChange(event) {
setData(data => ({ state: '', country: event.target.value }));
}

function handleStateChange(event) {
setData(data => ({ ...data, state: event.target.value }));
}

return (
<form onSubmit={() => console.log("Submitted")}>
<div>
<select value={country} onChange={handleCountryChange}>
{countries}
</select>
</div>

<div>
<select value={state} onChange={handleStateChange}>
{states}
</select>
</div>
<input type="submit" />
</form>
);
}

export default Form;

关于reactjs - 使用 React Hooks 的级联下拉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64495308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com