我正在关注文档here以创建受控组件下拉菜单。
我如何能够修改我的handleChange函数以使其知道它正在从“选择成员”下拉列表或“选择日期”下拉列表中接收值,以便我可以相应地更新状态值(“成员” “和”小时“?
import React, { Component } from 'react'
import { Dropdown, Grid } from 'semantic-ui-react'
class DropdownExampleRemote extends Component {
componentWillMount() {
this.setState({
optionsMembers: [
{ key: 1, text: 'DAILY', value: 'DAILY' },
{ key: 2, text: 'MONTHLY', value: 'MONTHLY' },
{ key: 3, text: 'WEEKLY', value: 'WEEKLY' },
],
optionsDays: [
{ key: 1, text: 'SUNDAY', value: 'SUNDAY' },
{ key: 2, text: 'MONDAY', value: 'MONDAY' },
{ key: 3, text: 'TUESDAY', value: 'TUESDAY' },
],
value: '',
member: '',
hour: '',
})
}
handleChange = (e, { value }) => {
this.setState({ member: value })
}
render() {
const {optionsMembers, optionsDays, value } = this.state
return (
<Grid>
<Grid.Column width={6}>
<Dropdown
selection
options={optionsMembers}
value={value}
placeholder='Select Member'
onChange={this.handleChange}
/>
</Grid.Column>
<Grid.Column width={6}>
<Dropdown
selection
options={optionsDays}
value={value}
placeholder='Select Day'
onChange={this.handleChange}
/>
</Grid.Column>
<Grid.Column width={4}>
<div>{this.state.member}</div>
<div>{this.state.day}</div>
</Grid.Column>
</Grid>
)
}
}
export default DropdownExampleRemote
更新 解决方案已经努力更新状态。仍然不确定为什么Dropbox的选择不会坚持并默认为占位符。
答案 0 :(得分:4)
我建议您将要更新的值的名称传递给句柄更改功能,例如:
import React, { Component } from 'react'
import { Dropdown, Grid } from 'semantic-ui-react'
class DropdownExampleRemote extends Component {
componentWillMount() {
this.setState({
optionsMembers: [
{ key: 1, text: 'DAILY', value: 'DAILY' },
{ key: 2, text: 'MONTHLY', value: 'MONTHLY' },
{ key: 3, text: 'WEEKLY', value: 'WEEKLY' },
],
optionsDays: [
{ key: 1, text: 'SUNDAY', value: 'SUNDAY' },
{ key: 2, text: 'MONDAY', value: 'MONDAY' },
{ key: 3, text: 'TUESDAY', value: 'TUESDAY' },
],
value: '',
member: '',
day: '',
})
}
handleChange = (value, key) => {
this.setState({ [key]: value });
}
render() {
const {optionsMembers, optionsDays, value, member, day } = this.state
return (
<Grid>
<Grid.Column width={6}>
<Dropdown
selection
options={optionsMembers}
value={member}
placeholder='Select Member'
onChange={(e,{value})=>this.handleChange(value, 'member')}
/>
</Grid.Column>
<Grid.Column width={6}>
<Dropdown
selection
options={optionsDays}
value={day}
placeholder='Select Day'
onChange={(e,{value})=>this.handleChange(value, 'day')}
/>
</Grid.Column>
<Grid.Column width={4}>
<div>{member}</div>
<div>{day}</div>
</Grid.Column>
</Grid>
)
}
}
export default DropdownExampleRemote
答案 1 :(得分:0)
这些方面的某些内容可能适合你。
handleChange = (propName, e) => {
let state = Object.assign({}, state);
state[propName] = e.target.value;
this.setState(state)
}
您可以传入要更新的属性的名称,然后使用括号表示法来更新您所在州的那部分。
希望这有帮助。