HTML + React:单选按钮卡在最初设置为“已选中"的按钮上.
我有一组两个单选按钮,其中一个在页面加载时被选中.看来我无法将其更改为第二个.如果重要的话,HTML 是由 reactjs 构建的.chrome 上的标记如下所示:
I have a set of two radio buttons one of which is checked when the page is loaded. It appears that I can't change it to the second one. The HTML is build by reactjs if that matters. The markup on chrome looks like:
<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 正在制作 input
的受控组件,因为每个输入的值都是从服务器端设置的.
The reason for this was that React was making the input
s controlled components because the values for each input are set from the server side.
引用 布兰登的回答:
如果您将 value={whatever}
属性添加到输入,使其成为受控组件,那么如果您添加 onChange
处理程序,用于更新 whatever
的值.来自 React 文档:
If you add a value={whatever}
property to the input, which makes it a controlled component, then it is read-only uness you add an onChange
handler that updates the value of whatever
. From the React docs:
为什么选择受控组件?
在 React 中使用诸如 <input>
之类的表单组件带来了编写传统表单 HTML 时所没有的挑战.例如,在 HTML 中:
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" />
这会渲染一个输入已初始化,其值为Untitled
.当用户更新输入时,节点的值 property 会改变.但是,node.getAttribute('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
.
与 HTML 不同,React 组件必须在任何时间点表示视图的状态,而不仅仅是在初始化时.例如,在 React 中:
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" />;
}
由于此方法描述了任何时间点的视图,因此文本输入的值应始终为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
s.
The simplest solution I found is to add onChange={function(){}}
to the input
s.
相关文章