【问题标题】:How to select a deafult choice with radio buttons - in React [duplicate]如何使用单选按钮选择默认选项 - 在 React [重复]
【发布时间】:2015-10-01 19:09:37
【问题描述】:

我想在收音机上选择一个默认值。我使用 v0.13.3,如果表达式计算结果为 true,则通过设置 checked 属性来尊重 checked={value===selected_value}

在生成的 HTML(由我格式化)中,匹配的单选按钮是 checkeded,但我无法选择任何其他按钮。

为什么会这样?设置选中选项的正确方法是什么?

  radio: function(value, selected_value, name, callback) {
    console.log("radio");
    console.log(value===selected_value);
    return(<label>
      <input type="radio" name="type" value={value} checked={value===selected_value}/>{name}
    </label>)
  },

  render: function() {
    selected_value = "com";
    return (
      <div>
        Options:
        <br/>
        {this.radio("cha", selected_value, "CM", null)}
        <br/>
        {this.radio("lea", selected_value, "L D", null)}
        <br/>
        {this.radio("com", selected_value, "Com", null)}
      </div>
    )

生成的 HTML:

<div data-reactid=".0"><span data-reactid=".0.0">Options:</span><br data-reactid=".0.1"><label data-reactid=".0.2">

<input name="type" value="cha" data-reactid=".0.2.0" type="radio"><span data-reactid=".0.2.1">CM</span></label><br data-reactid=".0.3"><label data-reactid=".0.4">

<input name="type" value="l" data-reactid=".0.4.0" type="radio"><span data-reactid=".0.4.1">L D</span></label><br data-reactid=".0.5"><label data-reactid=".0.6">

<input name="type" value="com" checked="" data-reactid=".0.6.0" type="radio"><span data-reactid=".0.6.1">Com</span></label></div>

【问题讨论】:

    标签: html reactjs


    【解决方案1】:

    通过手动设置checked 属性,您将创建Controlled Components,它不会响应用户输入,除非您明确定义onChange 事件处理程序来告诉组件在用户与其交互时要做什么。

    我相信您正在寻找的是 defaultChecked 道具。将此设置为 truefalse 将改为创建不受控制的组件,它将正常响应用户输入,同时仍为您提供所需的行为。

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多