class Province extends Component {
constructor(props) {
super(props)
}
handleChange(e) {
this
.props
.parentAction(e.target.value)
}
render() {
return (
<select onChange={this
.handleChange
.bind(this)}>
{this
.props
.value
.map((item, key) => (
<option value={item.zhou}>{item.zhou}</option>
))}
</select>
)
}
}
//城市选择框
class City extends Component {
render() {
return (
<select>
{this
.props
.value
.map(item => <option value={item}>{item}</option>)}
</select>
)
}
}
class Picker extends Component {
constructor(props) {
super(props)
this.state = {
province: [
{
id: 1,
zhou: "江苏",
country: ["南京", "苏州", "无锡"]
}, {
id: 2,
zhou: "安徽",
country: ["合肥", "芜湖"]
}
],
isProvince: "江苏",
isCity: ''
}
}
handleParentAction(value) {
this.setState({isProvince: value})
}
render() {
return (
<div>
<Province
value={this.state.province}
parentAction={this
.handleParentAction
.bind(this)}/>
<City
value={this
.state
.province
.find((item) => {
return (item.zhou == this.state.isProvince)
})
.country}/>
</div>
)
}
}
基于react的省份和市的二级联动,处理数据替换父组件中的province即可
注意点是: isPrivince这个state一定要设置成默认选中的那个省
改进版本
class ProvinceCity extends Component {
constructor(props) {
super(props)
this.state = {
priciList: [
{
id: 0,
province: '请选择省份',
cities: ['请选择城市']
}, {
id: 1,
province: '安徽',
cities: ['芜湖', '合肥']
}
],
provinceSelected: '请选择省份',
citySelected: ''
}
}
handleProvinceChange(e) {
this.setState({provinceSelected: e.target.value})
}
handleCityChange(e) {
this.setState({citySelected: e.target.value})
}
handleProvinceBlur(e) {
this
.props
.parentAction({province: e.target.value})
}
handleCityBlur(e) {
this
.props
.parentAction({city: e.target.value})
}
render() {
return (
<div>
<select
onChange={this
.handleProvinceChange
.bind(this)}
onBlur={this
.handleProvinceBlur
.bind(this)}>
{this
.state
.priciList
.map((item, key) => (
<option value={item.province} key={key}>{item.province}</option>
))}
</select>
<select
onChange={this
.handleCityChange
.bind(this)}
onBlur={this
.handleCityBlur
.bind(this)}>
{this
.state
.priciList
.find((item, key) => (item.province == this.state.provinceSelected))
.cities
.map((item, key) => (
<option value={item} key={key}>{item}</option>
))}
</select>
</div>
)
}
}
class Parent extends Component {
constructor(props) {
super(props)
this.state = {
province: '',
city: ''
}
}
handleParentAction(value) {
value.city
? this.setState({city: value.city})
: this.setState({province: value.province})
}
handleClick() {
console.log(this.state.province, this.state.city)
}
render() {
return (
<div>
<ProvinceCity
parentAction={this
.handleParentAction
.bind(this)}/>
<input value="点击"
type="button"
onClick={this
.handleClick
.bind(this)}/>
</div>
)
}
}