我正在使用Material UI的ToggleButtonGroup功能,但是我无法弄清楚如何将值传递到React的状态。下面是我的代码,我可以正确更改状态的日期,但是不能。我希望ToggleButtonGroup可以像Select在这里一样工作,因为它与我的UI更好地匹配。请在这里帮助我确定我在做什么错误。
state = {
text: '',
date: ''
}
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit = (event) => {
event.preventDefault()
// If input field empty, do nothing.
if (this.state.text === '') {
return
}
// Submit the form. (Add category here?)
this.props.onSubmit({
id: shortid.generate(),
text: this.state.text,
date: this.state.date,
complete: false
})
// Empty out input field after todo has been submitted.
this.setState({
text: ''
})
}
<Select onChange={this.handleChange} name="date" id="date-select" variant="standard">
<MenuItem value=""></MenuItem>
<MenuItem value="today">Today</MenuItem>
<MenuItem value="tomorrow">Tomorrow</MenuItem>
<MenuItem value="week">This week</MenuItem>
</Select>
<ToggleButtonGroup onChange={this.handleChange} value="date" name="date" id="date-select" exclusive={true} size="small">
<ToggleButton value="today">Today</ToggleButton>
<ToggleButton value="tomorrow">Tomorrow</ToggleButton>
<ToggleButton value="week">This week</ToggleButton>
</ToggleButtonGroup>
答案 0 :(得分:1)
在ToggleButtonGroup
回调中使用onChange
时,预期有两个参数,第一个是事件,另一个是选择的值,我们可以自定义该参数
handleChange = (name, newValue /*Value of the selected button*/) => {
console.log(newValue); //value of the selected button
this.setState({
[name]: newValue
})
}
因此,如果handleChange
和Select
是ToggleButtonGroup
和<Select onChange={(e) => this.handleChange("date", e.target.value)} ...
<ToggleButtonGroup onChange={(e, value) => this.handleChange("date", value)}..
的共同点,请像这样更改它。
{{1}}