【发布时间】:2021-01-15 23:00:53
【问题描述】:
我正在尝试制作一个充满<input> 标签的网页,人们可以在其中在编辑和只读模式之间切换。我怎么能轻松做到这一点,我的猜测是使用 <input> 的 value 属性?
【问题讨论】:
-
您是否尝试在输入中添加
readonly或readonly={true}?
标签: javascript html reactjs typescript
我正在尝试制作一个充满<input> 标签的网页,人们可以在其中在编辑和只读模式之间切换。我怎么能轻松做到这一点,我的猜测是使用 <input> 的 value 属性?
【问题讨论】:
readonly 或readonly={true}?
标签: javascript html reactjs typescript
您可以创建一个状态变量isEditMode=true 并创建一个将状态值更改为真或假的按钮。现在您可以使用此变量并将其值作为禁用属性传递,如下所示:-
<input disabled={!isEditMode}/>
因此,如果它不在编辑模式下,那么输入将被禁用,或者我们可以说在查看模式下。
【讨论】:
这是一个小示例,说明如何创建一个类,该类将自动生成输入并在需要时将其更新为只读。 (在小提琴上有一个工作示例)。只需连接一个按钮即可将输入更新为
编辑:这个解决方案最适合在 vanilla js 中使用
https://jsfiddle.net/0hvjr2uL/25/
class Inp {
constructor(name, value, placeholder, id, readOnly = false) {
this.name = name;
this.value = value;
this.placeholder = placeholder;
this.id = id;
this.readOnly = readOnly;
}
render(root){
let input = document.createElement("input");
input.name = this.name;
input.value = this.value
input.id = this.id;
input.setAttribute("readonly", this.readOnly);
root.appendChild(input);
}
update() {
let input = document.getElementById(this.id);
input.setAttribute("readonly", this.readOnly);
}
}
【讨论】: