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

时间:2016-02-17 08:21:11

标签: javascript jquery reactjs radio-button components

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

基本上,我有一张占用者表'细节,我希望能够指出其中一个是主要的。这些值在mysql db中存储和检索。我对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>
        );
    }
});

1 个答案:

答案 0 :(得分:1)

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);
    },