【问题标题】:Replacing a single value in array stored in state with user input --Reactjs用用户输入替换存储在状态中的数组中的单个值--Reactjs
【发布时间】:2018-04-06 02:51:08
【问题描述】:

我正在创建一个反应 madlibs 应用程序,我想在用户输入单词时一次更新 this.state.blanks 数组一项。我想我一定是绑定有问题(但我认为有胖箭头函数绑定它)?或者我只是以错误的方式解决了这个问题。

使用我现在的代码,我一直收到错误 "cannot read property 'value' of undefined"(指的是 e.target.valuehandleEnterWord 函数中)

这是我的代码有问题的部分现在的样子。

  state = {
    error: null,
    isLoaded: false,
    title: null,
    blanks: [noun, adjective, verb, etc],
    value: [],
    filledBlanks: []
  };

  handleEnterWord = (e, index) => {
    const word = e.target.value
    const newBlanks = [...this.state.blanks]
    newBlanks[index] = word
    this.setState({blanks: newBlanks})
    console.log(word, newBlanks)
  }

  render() {
    return (
      <div className="App">
        <button onClick = {this.handleNewMadlib}>New MadLib</button>
        <h1>{this.state.title}</h1>
        {this.state.blanks.map((blank, key) => {
          return <input key={key} placeholder={blank} onChange={()=>this.handleEnterWord(e, key)}/>
        })}

编辑:我在空白数组中添加了一些值,因为我认为这个问题有点模棱两可——这将由实际应用程序中的 API 调用填写

欢迎任何帮助/建议。 在此先感谢:)

【问题讨论】:

    标签: arrays reactjs event-handling state


    【解决方案1】:

    我相信你的问题出在

     onChange={()=>this.handleEnterWord(e, key)}
    

    你应该像这样将事件传递给函数

     onChange={(e)=>this.handleEnterWord(e, key)}
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2019-01-12
      • 1970-01-01
      相关资源
      最近更新 更多