不能在表格中使用函数反应js

时间:2017-06-18 13:18:21

标签: reactjs

constructor(props) {
  super(props);
  this.submitQA = this.submitQA.bind(this);
  this.onSearchChange = this.onSearchChange.bind(this);
  this.isSearched = this.isSearched.bind(this);
  this.answerSubmitted = this.answerSubmitted.bind(this);
  this.state = {
    answers: [],
    answer: '',
    searchTerm: '',
  }
}

answerSubmitted(event) {
 event.preventDefault();
 const input = event.target.querySelector('input');
 const value = input.value;
 const updatedList = this.state.answer;
 updatedList.push(value);
 this.setState({ answer: updatedList });
}



 render() {
    return (
    <div className="App">
      <div className="center">

        <form >
          Search:  <input type="text" onChange={this.onSearchChange}  /><br/>
        </form>

        <form onSubmit={this.submitQA}>
          Q & A:
          <input type="text" placeholder=" Course/Q/A"/>
          <button type="submit"> Submit </button>
        </form>
          <span>{basicFormat}</span>
      </div>

{ this.state.answers.filter(this.isSearched(this.state.searchTerm)).map(function(item) {
return (
    <div>
      <form >
        <text> {item} </text>
        <input onSubmit={this.answerSubmitted} type="text" placeholder="answer the question"/>
      </form>
    </div>
)
  }
    )
      }
      </div>
    );
  }
}

为什么我不能在这里使用这个功能?错误:无法读取属性&#39; answerSubmitted&#39;未定义的。不确定为什么会发生这种情况已经尝试过搜索,但我能找到的只是人们没有绑定我所做的方法。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您传递给map的功能会更改this上下文。请改用箭头功能:

{this.state.answers.filter(this.isSearched(this.state.searchTerm)).map((item) => (
  <div>
    <form>
      <text> {item} </text>
      <input onSubmit={this.answerSubmitted} type="text" placeholder="answer the question"/>
    </form>
  </div>
))}

箭头函数始终与定义它们的上下文具有相同的this。但是,其他函数会根据它们的调用方式更改this值。