【问题标题】:React - Can't Uncheck Radio ButtonReact - 无法取消选中单选按钮
【发布时间】:2016-05-28 20:06:12
【问题描述】:

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

基本上,我有一张住户详细信息表,我希望能够将其中一个指定为主要住户。这些值在 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>
        );
    }
});

【问题讨论】:

  • 您粘贴的类只是表格中的一行,对吧?我假设你有一个多次使用这个的父组件?如果是这样,您能否也发布父组件。

标签: javascript reactjs components radio-button


【解决方案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);
    },

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 2013-10-14
    • 1970-01-01
    • 2016-05-25
    • 2021-01-29
    • 1970-01-01
    • 2012-01-23
    • 2012-03-17
    相关资源
    最近更新 更多