除非我提供onChange回调,为什么反应会使输入[type =" text"]字段只读? [英] Why does react make input[type="text"] fields readonly unless I supply onChange callback?
问题描述
最初我有:
<input type="text"id="requested" name="requested" ref="requested" />
readonly 。
将其更改为:
<input type="text" onChange={function() {}} id="requested" name="requested" ref="requested" />
让它接受来自键盘的输入。为什么会发生这种情况?
made it accept input from keyboard. Why does this happen?
推荐答案
您列出的示例不是只读的。请参阅此JSFiddle: http://jsfiddle.net/BinaryMuse/13sbw3dy/
The example you list is not read-only. See this JSFiddle: http://jsfiddle.net/BinaryMuse/13sbw3dy/
如果您将 value = {whatever}
属性添加到输入中,这使其成为受控组件,然后将其读取 - 只有你添加一个 onChange
处理程序,它会更新的值
。来自 React docs :
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中输入>
表示在编写传统表单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" />
这会使输入初始化的值为无标题
。当用户更新输入时,节点的值属性将更改。但是, node.getAttribute('value')
仍将返回初始化时使用的值,无标题
。
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" />;
}
由于此方法描述了任何时间点的视图,因此该值为文本输入总是 无标题
。
Since this method describes the view at any point in time, the value of the text input should always be Untitled
.
这篇关于除非我提供onChange回调,为什么反应会使输入[type =" text"]字段只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!