HTML + React:单选按钮卡在最初设置为 "checked" 的按钮上

HTML + React: Radio button stuck on the one initially set as "checked"

我有一组两个单选按钮,其中一个在加载页面时被选中。看来我无法将其更改为第二个。如果重要的话,HTML 是由 reactjs 构建的。 chrome 上的标记如下所示:

<fieldset data-reactid=".0.0.0.0.0.0.1">
<label for="coop-radio-btn" data-reactid=".0.0.0.0.0.0.1.0">
    <span data-reactid=".0.0.0.0.0.0.1.0.0">To a Cooperative</span>
    <input type="radio" name="requestOnBehalfOf" value="coop" id="coop-radio-btn" data-reactid=".0.0.0.0.0.0.1.0.1">
</label>
<label for="union-radio-btn" data-reactid=".0.0.0.0.0.0.1.1">
    <span data-reactid=".0.0.0.0.0.0.1.1.0">Additional Request</span>
    <input type="radio" name="requestOnBehalfOf" value="union" checked="" id="union-radio-btn" data-reactid=".0.0.0.0.0.0.1.1.1">
</label>
</fieldset>

原因是 React 正在制作 inputs 受控组件,因为每个输入的值都是从服务器端设置的。

引用自

如果您向输入添加 value={whatever} 属性,使其成为受控组件,然后 它是只读的,除非您添加onChange 更新 whatever 值的处理程序。来自 the React docs:

Why Controlled Components?

Using form components such as <input> in React presents a challenge that is absent when writing traditional form HTML. For example, in HTML:

<input type="text" name="title" value="Untitled" />

This renders an input initialized with the value, Untitled. When the user updates the input, the node's value property will change. However, node.getAttribute('value') will still return the value used at initialization time, Untitled.

Unlike HTML, React components must represent the state of the view at any point in time and not only at initialization time. For example, in React:

render: function() {
  return <input type="text" name="title" value="Untitled" />;
}

Since this method describes the view at any point in time, the value of the text input should always be Untitled.

我找到的最简单的解决方案是将 onChange={function(){}} 添加到 input

更新 "the react way" 这样做是将 defaultChecked={true} 添加到所需的输入中。其他方式如下。

其实我也遇到过同样的情况。我所做的是在父 React 组件的 componentDidMount lifecycle method 中找到 input 标签,然后设置 checked 属性。

如果我们谈论 vanilla JS,您可以使用 querySelector 找到第一个无线电输入。像这样:

var Form = React.createClass({
    componentDidMount: function(){
        this.getDOMNode().querySelector('[type="radio"]').checked = "checked";
    },
    render: function(){
        //your render here
    }
});

如果你使用jQuery,可以这样做:

...
    $(this.getDOMNode()).find('[type="radio"]').eq(0).prop("checked", true);
...

我以前也遇到过类似的问题

defaultChecked 属性用于(且仅用于)第一次渲染,并提供一个 onChange 函数来处理值更改。

我在这里为不同的 input 类型找到了一个很好的例子:http://bl.ocks.org/insin/raw/082c0d88f6290a0ea4c7/

像这样使用defaultChecked

<input type="radio" name="temperature" value="hot" defaultChecked={true}/> Hot
<input type="radio" name="temperature" value="warm" /> Warm