简体   繁体   English

React我无法更改输入字段的值(如果它具有值)和onChange

[英]React I can't change my input field's value if it has a value and onChange

I have a CRUD application, in my component's state I save the name of the user. 我有一个CRUD应用程序,在我的组件的状态我保存用户 Now the problem is: I have an input field for name in my form and when the user clicks on update user from the list, the selected user's name will appear on the input field and then I'm unable to change the name because the input field won't let me. 现在的问题是:我在表单中有一个输入名称的字段,当用户从列表中单击“ 更新用户”时,所选用户的名称将出现在输入字段中,然后由于输入而无法更改名称场不会让我。 I delete a letter and it reappears automatically, how can I fix this? 我删除了一个字母,它会自动重新出现,该如何解决?

In my component's render method: 在我组件的render方法中:

 <div className="col-sm-9">
      <div className="form-check">
          <input name="user_name" ref="user_name" className="form-check-input" type="checkbox" value="1" id="user_name"
                 value={this.state.user_name} onChange={this.onChange} />          
      </div>
  </div>

Outside my render method: 在我的渲染方法之外:

onChange(e) {
    this.setState({[e.target.name]: e.target.value})
}

Have you bind your onChange method(i suppose that is the issue, that your state is not getting updated). 您是否绑定了onChange方法(我想这是问题所在,您的状态没有得到更新)。 If not, then : try changing to this : 如果没有,请尝试更改为:

onChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
}

Or to this : 对此:

<div className="col-sm-9">
      <div className="form-check">
          <input name="user_name" ref="user_name" className="form-check-input" type="checkbox" value="1" id="user_name"
                 value={this.state.user_name} onChange={this.onChange.bind(this)} />          
      </div>
  </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM