我正在從 api 接收資料,例如嵌套到狀態物件中的參考
例子:
const data = [
{
id: 1,
name: 'State One',
cities: [
{
id: 1,
state: 'State One',
name: 'City One'
},
{
id: 2,
state: 'State One',
name: 'City Two'
},
{
id: 3,
state: 'State One',
name: 'City Three'
}
]
},
{
id: 2,
name: 'State 2',
cities: [
{
id: 4,
state: 'State 2',
name: 'City 5'
}
]
}
]
I have to give the Select options of the Cities according to Parent State. Lets say User selected State One in State Select Field then There should be only cities options of the State One in next City Field
I can I configure.
Currently; I have created hollow structure of the Select Input Fields but can't find anything how can I configure it. I need little help or any idea to start with.
This is current code;
<Col lg="6" md="12" className="mb-1">
<Label className="form-label py-1" for="state">
State
</Label>{' '}
<Row></Row>
<Select
id="state"
options={stateOptions}
defaultValue={stateOptions[0]}
onChange={(choice) => console.log(choice.value)}
/>
</Col>
<Col lg="6" md="12" className="mb-1">
<Label className="form-label py-1" for="city">
City
</Label>{' '}
<Row></Row>
<Select
id="city"
classNamePrefix="select"
options={cityOptions}
onChange={(choice) => console.log(choice.value)}
/>
</Col>
I have seen some articles but they suggst to use npm libraries but I can't use them because data is a lot different that I want to handle.
uj5u.com熱心網友回復:
您可以跟蹤當前選定的州并更新第二個 Select 所采用的城市。
還添加了一些注釋來解釋這些函式的作用。
export default function App() {
const [state, setState] = useState(null);
const [city, setCity] = useState(null);
const onStateChange = (option) => {
setState(option);
// to remove city if a different state is selected
if (!option || option?.value !== state?.value) setCity(null);
};
const onCityChange = (option) => {
setCity(option);
};
// a separate useState for cities is not needed
// as cities depend on the selected state, it can be determined when state changes
const cities = useMemo(() => {
if (!state) return [];
return getOptions(data.find((el) => el.id === state.value).cities);
}, [state]);
return (
<div>
<Select options={states} value={state} onChange={onStateChange} />
<hr />
<Select options={cities} value={city} onChange={onCityChange} />
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451890.html
標籤:javascript reactjs react-select
上一篇:使用過濾器時如何獲得某些物體屬性
下一篇:無法呈現陣列的值(jquery)
