React子组件调用父组件onDelete方法报‘is not a function’错误
问题解决方法
你遇到的Uncaught TypeError: this.props.onDelete is not a function错误,核心原因是App组件没有将onDelete方法通过props传递给Bottom组件,导致Bottom组件中this.props.onDelete是undefined,自然无法作为函数调用。
解决步骤
在App组件的render方法里,渲染<Bottom/>时手动传入onDelete属性,把App的onDelete方法作为值传递过去即可:
<Bottom onDelete={this.onDelete} />
修改后的完整代码
HTML部分
<div id="app"></div>
JS部分
class App extends React.Component { constructor(props) { super(props); } onDelete() { let word = "hi"; console.log(word); return word; } render() { return ( <div>Hello React..! {this.onDelete()} <br/>Time: {new Date(Date.now()).toISOString()} <br/><Bottom onDelete={this.onDelete} /> </div> ); } } class Bottom extends React.Component { constructor(props) { super(props); this.handleDelete = this.handleDelete.bind(this); } handleDelete() { this.props.onDelete(); } render() { return(<div> <button onClick={this.handleDelete}>Delete</button> </div>); } } React.render(<App />, document.getElementById('app'));
额外说明
如果后续onDelete方法内部需要访问App组件的实例(比如读取state),还需要给方法绑定this,有两种常用方式:
- 在构造函数中绑定:
constructor(props) { super(props); this.onDelete = this.onDelete.bind(this); } - 用箭头函数定义方法:
onDelete = () => { // 此处可直接使用this访问组件实例 }
内容的提问来源于stack exchange,提问作者Rash
相关产品推荐
相关产品推荐

