ReactJs : 如何在 RegionDrop 中选择默认值。
我正在使用"反应国家/地区选择器",其中有两个组件"国家下拉列表"和"区域下拉列表"。现在在构造函数中,我选择了默认值"国家下拉列表"。但我的要求是,当我从国家/地区列表中选择任何值时,regionDropdown 将使用默认值填充列表中的名字。
这是我尝试过的代码:步骤 1:导入反应国家/地区选择器
第 2 步:在我的代码中使用这些组件。
在构造函数中,我设置了国家的初始值 国家:"美国">
这是我通过的链接:
https://www.npmjs.com/package/react-country-region-selector#demo
import { CountryDropdown, RegionDropdown, CountryRegionData } from 'react-country-region-selector';
<tr>
<td><label><CountryDropdown value={this.state.country}
onChange={(val) => this.selectCountry(val)} />
</label>
</td>
<td><label><RegionDropdown country={this.state.country}
value={this.state.region}onChange={(val) => this.selectRegion(val)}/>
</label>
</td>
</tr>
selectCountry (val) {
this.setState({ country: val });
}
selectRegion (val) {
this.setState({ region: val });
}
//And in the constructor i set the initial value of country
country: 'United States'
我期望的是"区域下拉列表"默认情况下将始终与列表中的第一个值一起出现。例如:在渲染时,它将是"阿拉巴马州",因为默认国家是"美国"。
从 th 文档中,
是否要显示默认选项。这是用户在选择国家/地区后在区域下拉列表中看到的内容。
根据您的要求,
我期望的是"区域下拉列表"默认情况下将始终与列表中的第一个值一起出现。
您需要将其设置为RegionDropdown
,
showDefaultOption={false}
默认情况下,CountryRegionData
可以使用,当您使用react-country-region-selector
安装时,
npm i react-country-region-selector
yarn add react-country-region-selector
这是我的代码,工作正常,
import React, { Component } from "react";
import { CountryDropdown, RegionDropdown, CountryRegionData } from 'react-country-region-selector';
class App extends Component {
constructor(props) {
super(props);
this.state = { country: 'United States', region: '' };
}
selectCountry(val) {
this.setState({ country: val });
}
selectRegion(val) {
this.setState({ region: val });
}
render() {
const { country, region } = this.state;
return (
<div>
<table>
<tbody>
<tr>
<td>
<label>
<CountryDropdown
value={this.state.country}
onChange={(val) => this.selectCountry(val)} />
</label>
</td>
<td>
<label>
<RegionDropdown
country={this.state.country}
value={this.state.region}
onChange={(val) => this.selectRegion(val)}
showDefaultOption={false}/> //To see first option by default
</label>
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
注意:如果在选择CountryDropdown
后无法看到RegionDropdown
,则必须尝试重新安装react-country-region-selector
。 默认情况下,CountryRegionData
可用。您始终可以在导入语句后确认数据是否可用console.log(CountryRegionData)
。