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

React实现返回按钮跳转失败:子传父函数报is not a function错误

React子组件调用父组件函数报错的解决方案

嘿,我看你遇到了React里子组件调用父组件函数时报错_this.props.callHomeFunction is not a function的问题,结合你给出的代码,我帮你梳理下问题根源和修复步骤:

问题根源分析

从你的代码来看,主要有两个核心问题:

  1. 父组件传递props的目标组件错误:你在父组件里渲染的是<Select callHomeFunction={this.consoleToHome} />,但你的子组件是BackButton类——这意味着BackButton根本没接收到callHomeFunction这个props,自然会报错说它不是函数。
  2. 多余的函数绑定冲突:你在constructor里写了this.consoleToHome = this.consoleToHome.bind(this),但又用了类字段箭头函数定义consoleToHome = (test) => {...},箭头函数本身会自动绑定this,这行bind代码不仅多余,还可能导致函数引用混乱。

修复步骤

1. 修正父组件的渲染组件

把父组件里的<Select>改成你的子组件<BackButton>,确保props传递给正确的组件。

2. 移除多余的函数绑定

删掉constructor里的this.consoleToHome = this.consoleToHome.bind(this),因为箭头函数已经帮你绑定好this了。

修正后的完整代码

Parent.js

import React, { Component } from 'react';
import { Router } from 'react-router-dom';
import BackButton from './Child'; // 确保子组件路径正确

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      okRedirect: false, 
    };
    // 移除多余的bind代码
  }

  // 类字段箭头函数自动绑定this,无需额外处理
  consoleToHome = (test) => { 
    // this.setState({ okRedirect: true }); 
    console.log('go to home'); 
    console.log(test); 
  }

  render(){ 
    return( 
      <Router> 
        {/* 传递props给正确的BackButton组件 */}
        <BackButton callHomeFunction={this.consoleToHome} /> 
      </Router>
    );
  }
}

export default Parent;

Child.js

import React, { Component } from 'react';

class BackButton extends Component { 
  changePage = () => { 
    const test = 'test'; 
    console.log('click on home'); 
    console.log(this.props); 
    // 现在能正确拿到父组件传递的函数了
    this.props.callHomeFunction(test); 
  }

  render() { 
    return ( 
      <div className='back_buttons'> 
        <ul> 
          <li> 
            <button className='back_buttons back_button' onClick={this.changePage}>返回首页</button> 
          </li> 
        </ul> 
      </div> 
    ); 
  }
}

export default BackButton;

额外说明

如果你的场景是BackButton是Select组件的子组件,那需要确保Select组件把callHomeFunctionprops透传给BackButton,比如在Select组件的render里写:

<BackButton callHomeFunction={this.props.callHomeFunction} />

这样BackButton才能拿到父组件传递的函数。

内容的提问来源于stack exchange,提问作者PandaMastr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:52:55