You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 04:28:10