React - 无法取消选中单选按钮

React - Can't Uncheck Radio Button

我不知道我做错了什么,但我无法取消选中当前单选按钮或 select 其他单选按钮。

基本上,我有一份 table 住户的详细信息,我希望能够将其中之一指定为主要住户。这些值在 mysql 数据库中存储和检索。我对 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 处理程序 primaryOccupantClicked 基本上是一个切换函数,因此您想将状态设置为与当前状态相反(即 !this.state.primary_occupant)。这将解决问题:

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

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