简体   繁体   English

反应 - 无法取消选中单选按钮

[英]React - Can't Uncheck Radio Button

I don't know what I'm doing wrong, but I'm unable to uncheck current radio button or select other radio buttons. 我不知道我做错了什么,但我无法取消选中当前的单选按钮或选择其他单选按钮。

Basically, I have a table of occupants' details and I want to be able to indicate one of them as primary. 基本上,我有一个占用者的详细信息表,我希望能够指出其中一个是主要的。 The values are stored and retrieved in an mysql db. 这些值在mysql db中存储和检索。 I am relatively new to ReactJS. 我对ReactJS比较陌生。

var PrimaryOccupantInput = React.createClass({
    getInitialState: function()
    {
        return {
            primary_occupant: (!(this.props.primary_occupant == null || this.props.primary_occupant == false))
        };
    },
    primaryOccupantClicked: function()
    {
        this.setState({
            primary_occupant: this.state.primary_occupant
        });

        this.props.primaryOccupantClicked(this.props.booking_occupant_id, this.state.primary_occupant.checked);
    },
    render: function() {
        var is_primary = "";

        if(this.state.primary_occupant != null)
        {
            if(this.state.primary_occupant == true)
            {
                is_primary = <span className="text-success">Yes</span>;
            }
            else if(this.state.primary_occupant == false)
            {
                is_primary = <span className="text-danger">No</span>;
            }
            else
            {
                is_primary = this.state.primary_occupant;
            }
        }
        else
        {
            is_primary = <span className="text-muted"><em>undefined</em></span>;
        }

        return (
            <div>
                <input type="radio" id="primary_occupant" name="primary_occupant[]" ref="primaryOccupantCheckbox" checked={this.state.primary_occupant} onChange={this.primaryOccupantClicked} />&nbsp;|&nbsp;
                {is_primary}
            </div>
        );
    }
});

onChange handler primaryOccupantClicked is basically a toggle function, so you want to set state opposite to current state (ie !this.state.primary_occupant ). onChange handler primaryOccupantClicked基本上是一个切换函数,所以你想设置与当前状态相反的状态(即!this.state.primary_occupant )。 This will fix the issue: 这将解决问题:

primaryOccupantClicked: function()
    {
        this.setState({
            primary_occupant: !this.state.primary_occupant
        });

        this.props.primaryOccupantClicked(this.props.booking_occupant_id, this.state.primary_occupant.checked);
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM