我有三个素材ui下拉列表。我想当我选择一个状态值更改时,这部分是正常的,但它是不正确的,因为它更改了其他下拉菜单的值我该如何解决这个问题?
import React,{Component} from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
class DateOfBirth extends Component{
constructor(props){
super(props)
this.state ={
year: '2005',
month: '08',
day: '10',
value: 1
}
}
handleChange = (event, index, value) => {
this.setState({value});
}
componentWillMount(){
const {date} = this.props
console.log(date)
}
render(){
return(
<div>
<p>Date Of Birth</p>
<DropDownMenu
value={this.state.value}
onChange={this.handleChange}>
<MenuItem value={1} primaryText="Year" />
<MenuItem value={this.state.year} primaryText={this.state.year} />
</DropDownMenu>
<DropDownMenu
value={this.state.value}
onChange={this.handleChange}
>
<MenuItem value={1} primaryText="Month" />
<MenuItem value={this.state.month} primaryText={this.state.month}/>
</DropDownMenu>
<DropDownMenu
value={this.state.value}
onChange={this.handleChange}
>
<MenuItem value={1} primaryText="Day" />
<MenuItem key="day" value={this.state.day} primaryText={this.state.day} />
</DropDownMenu>
</div>
)
}
}
export default DateOfBirth
答案 0 :(得分:1)
原因是,您使用单个state
变量来控制三个下拉菜单,而不是使用三个单独的state
值,每个下拉菜单一个。
像这样:
this.state ={
year: '2005',
month: '08',
day: '10',
value1: 1,
value2: 1,
value3: 1
}
像这样编写render
方法:
render(){
return(
<div>
<p>Date Of Birth</p>
<DropDownMenu
value={this.state.value1}
onChange={(e, i, value) => this.setState({value1: value})}>
<MenuItem value={1} primaryText="Year" />
<MenuItem value={this.state.year} primaryText={this.state.year} />
</DropDownMenu>
<DropDownMenu
value={this.state.value2}
onChange={(e, i, value) => this.setState({value2: value})}>
>
<MenuItem value={1} primaryText="Month" />
<MenuItem value={this.state.month} primaryText={this.state.month}/>
</DropDownMenu>
<DropDownMenu
value={this.state.value3}
onChange={(e, i, value) => this.setState({value3: value})}>
>
<MenuItem value={1} primaryText="Day" />
<MenuItem key="day" value={this.state.day} primaryText={this.state.day} />
</DropDownMenu>
</div>
)
}
注意:如果您使用的是常见的onChange方法,则将一些标识符与onChange绑定,以确定更改了哪个下拉列表并更新特定的状态值。
使用单个onChange方法进行更新:
render(){
return(
<div>
<p>Date Of Birth</p>
<DropDownMenu
value={this.state.value1}
onChange={(e, i, value) => this._handleChange('value1', value)}>
<MenuItem value={1} primaryText="Year" />
<MenuItem value={this.state.year} primaryText={this.state.year} />
</DropDownMenu>
<DropDownMenu
value={this.state.value2}
onChange={(e, i, value) => this._handleChange('value2', value)}>
>
<MenuItem value={1} primaryText="Month" />
<MenuItem value={this.state.month} primaryText={this.state.month}/>
</DropDownMenu>
<DropDownMenu
value={this.state.value3}
onChange={(e, i, value) => this._handleChange('value3', value)}>
>
<MenuItem value={1} primaryText="Day" />
<MenuItem key="day" value={this.state.day} primaryText={this.state.day} />
</DropDownMenu>
</div>
)
}
_handleChange(fieldName, value){
this.setState({
[fieldName]: value
});
}