我是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;}
我该怎么办
2条答案
按热度按时间qlvxas9a1#
如果您使用
ref
处理值,则使用defaultValue
而不是value
。input
上的defaultValue
prop允许您的 uncontrolled 组件设置初始值。value
要求您在每次渲染时设置该值。所以简单地改成这样:
5ktev3wc2#
如果按钮的值需要从比输入字段更多的地方更新,则可以将输入用作“受控组件”。要做到这一点,你可以创建一个“state variable“:
因此,您可以使用“setEditableValue”函数从任何其他位置编辑输入值。输入将具有这些参数:
每次使用“setEditableValue”函数时都会修改该值,并且每次在输入上写入内容时都会执行该函数。