繁体   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