簡體   English   中英

傳遞給 onChange 方法的子組件時出現“無法讀取未定義道具”的錯誤

[英]Getting error of "Cannot read props of undefined" when being passed to child component for onChange method

將 onchange 函數傳遞給子組件時,我收到“無法讀取未定義的道具”的錯誤,但是,當控制台記錄道具時,會顯示正確的屬性。

我以前這樣做過,我將一個 onClick 道具傳遞給了一個子按鈕,這似乎工作得很好。

錯誤消息僅在嘗試編輯字段時發生。

控制台記錄的道具

父組件

 //Parent component onChange = e => { e.preventDefault(); console.log(e); } render(){ return( <div className="App"> <div className="cardRow"> <Card question={this.state.currentCard.question} answer={this.state.currentCard.answer} source={this.state.currentCard.source} onClick={this.submitUpdate.bind(this)} recordChange={this.onChange.bind(this)}>{this.state.update}</Card> ..... //child component class Card extends Component { //the below code is where the error message is pointing recordChange(){ this.props.recordChange(); } onSubmit(){ this.props.onSubmit(); } render(props){ console.log(this.props); return( <div className="card-container"> {this.props.children? <div className="cardUpdate"> <form className="update-form"> <h5>Front</h5> <input type="text" value={this.props.question} onChange={this.recordChange}/> <h5>Answer</h5> <textarea type="text" value={this.props.answer} onChange={this.recordChange}/> <h5>Source</h5> <input type="text" value={this.props.source} onChange={this.recordChange}/> <div> <button onClick={this.props.onClick}>Submit</button> </div> </form> </div> : <div className="card"> <div className="front"> <div className="question">{this.props.question}</div> </div> <div className="back"> <div className="answer">{this.props.answer}</div> <div className="source">{this.props.source}</div> </div> </div> } </div> ); }

recordChange在類的上下文中無權訪問this

recordChange() {
  // 'this' is undefined.
  this.props.recordChange();
}

然而,正如你所注意到的, console.log(this.props); 內部render工作正常。 這是因為render在類的上下文中被調用; recordChange不是。

它變成一個箭頭的功能,使this在范圍:

recordChange = () => {
  this.props.recordChange();
}

或者在構造函數中將其綁定到this

constructor(props) {
  super(props);
  this.recordChange = this.recordChange.bind(this);
}

recordChange(){
  this.props.recordChange();
}

或者更好:

根本不要使用子函數。 如果它所做的只是從props調用函數,則沒有必要。 只需執行onChange={this.props.recordChange}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM