首页 > 解决方案 > React 父子通信:TypeError: _this.state.myFunction is not a function

问题描述

我是 React 世界的新手,我正在尝试使用应该从子组件调用的函数来构建父组件。但是,当我调用该函数时,我在标题中收到错误消息。我有类似的东西:

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myFunction = this.myFunction.bind(this);
  }

  myFunction(param) {
    //do something  
  }
  
  render(){
    return(
      <ChildComponent event={this.myFunction} />
    );
  }
 }
 
 
 class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inheritedFunction: this.props.event
    };
  }
  
  childFunction(param) {
    //do a few things first
    this.state.inheritedFunction(param);
  }
  
  render(){
    return(
     <input type="checkbox" onChange={this.childFunction.bind(this)></input>
    );
  }  
 }

我的代码编译并运行,然后当它在选中复选框时执行 childFunction() 时,this.state.inheritedFunction(param) 说它不是一个函数并且应用程序崩溃了。我怀疑它必须与绑定有关,但我真的不确定并坚持这个问题。

我是 React 的新手,所以请善待。:-) 有人知道我搞砸了什么吗?

标签: javascriptreactjsreact-nativeruntime-errorfrontend

解决方案


class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myFunction = this.myFunction.bind(this);
  }

  myFunction = (param) => {
    //do something  
    alert(param);
  }

  render(){
    return(
      <ChildComponent event={this.myFunction} />
    );
  }
 }


 class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inheritedFunction: this.props.event
    };
  }

  childFunction(param) {
    //do a few things first
    this.props.event(param);
  }

  render(){
    return(
     <input type="checkbox" onChange={this.childFunction.bind(this)></input>
    );
  }  
 }

推荐阅读