【发布时间】:2020-06-16 10:57:51
【问题描述】:
我有两个选择框,一个用于国家/地区,另一个用于地区。当有人选择一个国家时,我需要用不同的值(异步)填充区域选择。
我知道react-country-region-selector 和react-select,但是对于这样一个简单的任务,这些解决方案似乎有点过分了。
在下面的代码中,区域在选择国家后正确填充,但是国家选择的值丢失了。另外,我应该在构造函数中设置状态还是 Formik 应该处理所有状态?
import React from 'react';
import { Formik, Form, Field } from "formik";
class App extends React.Component {
constructor(props) {
super(props);
console.log(`props: ${JSON.stringify(props, null, 2)}`)
this.state = {
regions: []
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCountryChanged = this.handleCountryChanged.bind(this);
this.getRegions = this.getRegions.bind(this);
}
handleSubmit(values, { setSubmitting }) {
console.log(JSON.stringify(values), null, 2);
};
handleCountryChanged(event) {
const country = event.target.value;
this.getRegions(country).then(regions => {
this.setState({ regions: regions });
console.log(`regions: ${JSON.stringify(regions, null, 2)}`);
});
}
getRegions(country) {
// Simulate async call
return new Promise((resolve, reject) => {
switch (country) {
case "United States":
resolve([
{ value: 'Washington', label: 'Washington' },
{ value: 'California', label: 'California' }
]);
break;
case "Canada":
resolve([
{ value: "Alberta", label: "Alberta" },
{ value: "NovaScotia", label: "Nova Scotia" }
]);
break;
default:
resolve([]);
}
});
}
render() {
return (
<Formik
initialValues={{ country: "None", region: "None", regions: [] }}
onSubmit={this.handleSubmit}
>
{({ isSubmitting }) => (
<Form>
<label htmlFor="country">Country</label>
<Field id="country" name="country" as="select"
onChange={this.handleCountryChanged}>
<option value="None">Select country</option>
<option value="United States">United States</option>
<option value="Canada">Canada</option>
</Field>
<label htmlFor="region">Region</label>
<Field id="region" name="region" as="select">
<option value="None">Select region</option>
{this.state.regions.map(r => (<option key={r.value} value={r.value}>{r.label}</option>))}
</Field>
<button type="submit" disabled={isSubmitting}>Submit</button>
</Form>
)}
</Formik>);
}
}
export default App;```
【问题讨论】: