【问题标题】:React input state not updating with update function which sets state反应输入状态不使用设置状态的更新函数更新
【发布时间】:2018-12-12 17:13:23
【问题描述】:

我正在尝试在我的页面上获取一个模式,以根据组件的状态以及名为 onChange 的更新函数来获取和更新其值。

目前看起来是这样的:

constructor() {
  this.state = {
   name: '',
  }
}

updatedName = e => {
  this.setState({ name: e.target.value })
}

render() {
                <div className="modal__content__wrapper">
                    <div className="modal--display">
                        <label className='modal--label'> Name</label>
                        <input
                            className='modal--input'
                            onChange={this.updateName}
                            value={this.state.name}
                            />
                    </div>
                </div>
}

这似乎很基本,但我不确定我做错了什么。

【问题讨论】:

  • 它似乎只将状态更新为一个字母,然后每次都重写该字母,并且永远不会在输入中显示它。
  • onChange={() =&gt; this.updatedName}
  • 已解决。我需要将 value 属性更改为 defaultValue,一切正常。

标签: javascript reactjs onchange


【解决方案1】:
 onChange={this.updateName}

我认为您缺少 .bind(this)。试试看,

this.updateName.bind(this)

更新,

可能是你的函数名有错别字。

return 语句中有 this.updateName,函数定义中有 this.updatedName(注意 update"d"Name 中的 "d")。

【讨论】:

  • 是的,这是我在这里输入的拼写错误,但它不在我的代码中
【解决方案2】:

您缺少super()return()。此外,updatedName 在调用时拼写错误。

constructor() {
 super();
  this.state = {
   name: '',
  }
}

updatedName = e => {
 this.setState({ name: e.target.value })
}

render() {
 return(
   <div className="modal__content__wrapper">
     <div className="modal--display">
     <label className='modal--label'> Name</label>
       <input
         className='modal--input'
         onChange={this.updatedName}
         value={this.state.name}
       />
     </div>
    </div>
  )
 }

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2018-03-28
    • 2018-11-30
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多