单选按钮需要单击两次以反映更改

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)

小智 22

event.preventDefault();从您的handleOptionChange方法中删除


Lur*_*xel 13

对于遇到此问题的其他人,请确保您没有name对多组单选按钮使用相同的属性。

当通过数组映射并为每个数组项呈现一组单选按钮时,可能会发生这种情况。通过将当前数组项的索引添加到单选按钮名称来避免此问题。

请注意,在这种情况下preventDefaulthandleOptionChange方法中不需要。

  • 缺少渲染包裹单选按钮的“&lt;form&gt;”标签是我的罪魁祸首。有效地将我置于具有相同“名称”属性场景的多个组中。 (4认同)

小智 13

如果您使用 React,还要注意checked无线电输入中的标签属性。对我来说,当我想要默认选中的单选按钮时,错误设置的选中属性导致了此问题。

请参阅此内容以获取可能的修复方法。

更新:使用defaultChecked而不是checked修复它


Tom*_*iwa 8

例如,如果您像我一样需要使用 来event.preventDefault()阻止输入提交。你可以用event.stopPropagation()它代替。

请参阅此问题评论解释更多背景信息