2017-06-18 6 views
0
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> 
    ); 
    } 
} 

ここでは関数を使用しないのはなぜですか?エラー:未定義の 'answerSubmitted'プロパティを読み取ることができません。なぜこれが起こっているのか分かりませんでしたが、私が見つけたのは、人々が自分のやり方を縛らなかったことだけです。どんな助けもありがたい。フォームで関数を使用できない反応するjs

答えて

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の値を変更します。

関連する問題