Pra*_*idu 9 javascript reactjs
1.每当我点击单选按钮时,它会调用handleOptionChange回调,但不会反映html的变化.2.但是当我在单选按钮上单击两次时,它反映了更改
我的问题是为什么我需要在单选按钮上单击两次?我做错了吗?
class CompleteProfile extends Component{
constructor(props){
super(props);
this.state = {
teacher_role:'subject'
};
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(event){
event.preventDefault();
let { name, value } = event.target;
this.setState( { [name]:value } );
}
render(){
let { teacher_role } = this.state;
console.log('teacher:',teacher_role);
return(
<Wrapper className="complete-profile">
<CustomContainer>
<Title>complete profile</Title>
<ProfileCard>
<Form noValidate>
<FormGroup>
<label>I want to enroll as:</label>
<label htmlFor="test">
<input id="test" type="radio" name="teacher_role" value="subject" checked={ teacher_role === 'subject' } onChange={ this.handleOptionChange } />
subject teacher
</label>
<label htmlFor="test1">
<input id="test1" type="radio" name="teacher_role" value="chapter" checked={ teacher_role === 'chapter' } onChange={ this.handleOptionChange } />
class teacher
</label>
<label htmlFor="test2">
<input id="test2" type="radio" name="teacher_role" value="both" checked={ teacher_role === 'both' } onChange={ this.handleOptionChange } />
both
</label>
</FormGroup>
</Form>
</ProfileCard>
</CustomContainer>
</Wrapper>
)
}
componentWillUpdate(nextProps){
}
componentDidUpdate(prevProps){
}
}
Run Code Online (Sandbox Code Playgroud)
Lur*_*xel 13
对于遇到此问题的其他人,请确保您没有name对多组单选按钮使用相同的属性。
当通过数组映射并为每个数组项呈现一组单选按钮时,可能会发生这种情况。通过将当前数组项的索引添加到单选按钮名称来避免此问题。
请注意,在这种情况下preventDefault,handleOptionChange方法中不需要。
| 归档时间: |
|
| 查看次数: |
4142 次 |
| 最近记录: |