【问题标题】:Radio button not checked despite value being set in React尽管在 React 中设置了值,但未选中单选按钮
【发布时间】:2016-01-14 21:44:36
【问题描述】:

我确信我犯了一个小错误。我有一个带有两个单选按钮的 React 组件。

var OptionsBox = React.createClass({
    render: function(){
        console.log("Inside render");
        console.log(this.props.numberingPositionAtStart);
        return (
            <div>
                <div className="radio">
                    <label>
                        <input type="radio" name="radioNumberingPositionOptions" id="numberingPositionAtStart" value="1" onChange={this._onClick} checked={this.props.numberingPositionAtStart}  />
                Append numbering at the beginning of tweets
                    </label>
                </div>
                <div className="radio">
                    <label>
                        <input type="radio" name="radioNumberingPositionOptions" id="numberingPositionAtEnd" value="0" onChange={this._onClick} checked={!this.props.numberingPositionAtStart} />
                Append numbering at the end of tweets
                    </label>
                </div>
            </div>
        );
    },

    _onClick: function(event){
        if (event.target.value == 1)
            {
                TweetSmartActionCreator.numberingpositionatstart(true);
            }
        else{
            TweetSmartActionCreator.numberingpositionatstart(false);
        }

    }
});

控制台的输出是

Inside render
false

但是,它始终是始终选中的第一个单选按钮。即使在更改时,第一个单选按钮仍处于选中状态。

即使在第一次渲染期间,该值也是 false,因此应该检查第二个按钮,但事实并非如此。我该如何调试呢?

【问题讨论】:

  • 似乎按预期工作:jsfiddle.net/pgxkvw3t。我使用的是 Chrome 46 和 Safari 9
  • 当我在网页中使用它时,它确实可以按预期工作,如 tweetsmart.in/popup.html 所示,但我正在尝试制作一个 chrome 扩展并使用相同的代码,出于某种原因它确实如此那里似乎没有按预期工作。
  • 那么,请澄清您的问题并添加其他相关代码。这个 React 组件按预期工作。

标签: javascript reactjs


【解决方案1】:

您似乎正在传递 String 作为 numberingPositionAtStart 属性的值,例如 "false" 而不是布尔值 false

勾选这三行会选中第一个复选框:

React.render(<OptionsBox name="World" numberingPositionAtStart="true" />, document.body);

React.render(<OptionsBox name="World" numberingPositionAtStart="false" />, document.body);

React.render(<OptionsBox name="World" numberingPositionAtStart={true} />, document.body);

虽然以下行将呈现所需的结果:

React.render(<OptionsBox name="World" numberingPositionAtStart={false} />, document.body);

您可以在React docs阅读有关它的详细信息。

【讨论】:

  • 你是对的。由于将值存储在 localStorage 中,bool 变成了字符串,然后作为字符串传递!
猜你喜欢
  • 2021-03-07
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2020-08-10
  • 1970-01-01
  • 2020-06-15
相关资源
最近更新 更多