我在一个组件中有一个星期几的广播组。如果用户已经有一天与他们的帐户相关联,我希望那一天成为选中/选中的单选按钮。因此,如果他们之前保存了“星期一”,我将从父级获取它并将其存储在状态中,并希望在页面呈现时选择它。
我试图将其设置为类似于在用于选择的 React Forms 中完成的方式,但它似乎不适用于 Fieldset。有什么想法吗?
constructor(props) {
super(props);
this.state = {
reportWeekday: "monday"
}
}
handleWeekdayChange(event){
this.setState({reportWeekday: event.target.value});
console.log(event.target.value);
}
<fieldset className="schedule-weekday" value={this.state.reportWeekday} onChange={this.handleWeekdayChange}>
<label for="sunday"><input type="radio" name="schedule-weekly-option" value="sunday" id="sunday" />Sunday</label>
<label for="monday"><input type="radio" name="schedule-weekly-option" value="monday" id="monday" />Monday</label>
<label for="tuesday"><input type="radio" name="schedule-weekly-option" value="tuesday" id="tuesday" />Tuesday</label>
<label for="wednesday"><input type="radio" name="schedule-weekly-option" value="wednesday" id="wednesday" />Wednesday</label>
<label for="thursday"><input type="radio" name="schedule-weekly-option" value="thursday" id="thursday" />Thursday</label>
<label for="friday"><input type="radio" name="schedule-weekly-option" value="friday" id="friday" />Friday</label>
<label for="saturday"><input type="radio" name="schedule-weekly-option" value="saturday" id="saturday" />Saturday</label>
</fieldset>
最佳答案
这是 Jonny 在未启用类属性的情况下的解决方案。
class ControlledRadios extends React.Component{
constructor(){
super()
this.state = {
reportWeekday: 'monday'
}
}
handleWeekdayChange(event) {
this.setState({reportWeekday: event.target.value})
}
render() {
let {reportWeekday} = this.state
return (<fieldset onChange={this.handleWeekdayChange.bind(this)}>
<label><input type="radio" name="schedule-weekly-option" value="sunday" checked={reportWeekday === 'sunday'}/>Sunday</label>
<label><input type="radio" name="schedule-weekly-option" value="monday" checked={reportWeekday === 'monday'}/>Monday</label>
<label><input type="radio" name="schedule-weekly-option" value="tuesday" checked={reportWeekday === 'tuesday'}/>Tuesday</label>
<label><input type="radio" name="schedule-weekly-option" value="wednesday" checked={reportWeekday === 'wednesday'}/>Wednesday</label>
<label><input type="radio" name="schedule-weekly-option" value="thursday" checked={reportWeekday === 'thursday'}/>Thursday</label>
<label><input type="radio" name="schedule-weekly-option" value="friday" checked={reportWeekday === 'friday'}/>Friday</label>
<label><input type="radio" name="schedule-weekly-option" value="saturday" checked={reportWeekday === 'saturday'}/>Saturday</label>
</fieldset>)
}
}
关于javascript - React.js - 如何设置选中/选中的单选按钮并跟踪 onChange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44577673/