css 如何在reactjs中使具有值的输入字段可编辑?

cbjzeqam  于 12个月前  发布在  React
关注(0)|答案(2)|浏览(93)

我是Reactjs的新手,我很难让输入字段具有赋值。拜托,伙计们帮帮我。
我的js文件。

<div className="col-sm-9">
        <input className={this.state.editable ? "edit-profile" : "disable-profile disable"}
        ref="fullName"
        onChange={this._handleInputChange.bind(null, "fullName")}
                        value={user.fullName}/>

我的按钮

<button className="btn btn-default" onClick={this.edit}>
    {this.state.editDone ? "Done" : "Edit Profile"}</button>

edit = () => {
    if (!this.state.editDone) {
        this.setState({ editable: true, editDone: true});
    } else {
        this.setState({ editable: false, editDone: false});
    }
}

css文件

.edit-profile {
outline: 0;
color: #000000;
border-width: 0 0 1px 0;
border-color: #A9A9A9;
width: 30%;
background-color: transparent;
padding-left: 20px;
font-size: 12px;
margin-bottom: 20px;}

我该怎么办

qlvxas9a

qlvxas9a1#

如果您使用ref处理值,则使用defaultValue而不是value
input上的defaultValue prop允许您的 uncontrolled 组件设置初始值。
value要求您在每次渲染时设置该值。
所以简单地改成这样:

<input className={this.state.editable ? "edit-profile" : "disable-profile disable"}
        ref="fullName"
        onChange={this._handleInputChange.bind(null, "fullName")}
        defaultValue={user.fullName}/>
5ktev3wc

5ktev3wc2#

如果按钮的值需要从比输入字段更多的地方更新,则可以将输入用作“受控组件”。要做到这一点,你可以创建一个“state variable“:

const [editableValue, setEditableValue] = useState(value)

因此,您可以使用“setEditableValue”函数从任何其他位置编辑输入值。输入将具有这些参数:

<input value={editableValue} onChange={(e) => setEditableValue(e.target.value)} />

每次使用“setEditableValue”函数时都会修改该值,并且每次在输入上写入内容时都会执行该函数。

相关问题