通过 child 中的 props 调用 parent 的函数

Call function of parent through props in child

我想在子组件的另一个函数中调用一个父组件的函数(子函数将调用父组件的函数)。

我把父类的功能传给了子类。但是当代码编译时,我得到这个错误: Expected an assignment or function call and instead saw an expression no-unused-expressions.

class Parent extends Component {
  constructor() {
    ...
    this.someFunction = this.someFunction.bind(this);
  }
  
  // The child should call this function
  someFunction() {
    console.log("Doing something");
  }
  
  render() {
    return() {
      <Child doSomething={this.someFunction}>
    }
  }
}

class Child extends Component {
  constructor(props) {
    super(props);
    this.aChildFunction = this.aChildFunction.bind(this);
  }
  
  aChildFunction() {
    // Here is where I get the error
    this.props.doSomething;
  }
  
  render() {
    return() {
      <div>
        <button onClick={this.aChildFunction}>Click</button>
      </div>
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

我该如何解决?

您在调用函数时漏掉了括号“()”。

  aChildFunction() {
    // Call the function to execute
    this.props.doSomething();
  }

有几种方法可以做到这一点。

首先,您必须按照其他答案中所述调用该函数。

aChildFunction() {
  this.props.doSomething();
}

render() {
  return() {
    <div>
      <button onClick={this.aChildFunction}>Click</button>
    </div>
  }
}

您也可以直接将 doSomething 作为处理程序传递并跳过 aChildFunction

render() {
  return() {
    <div>
      <button onClick={this.props.doSomething}>Click</button>
    </div>
  }
}

在这种情况下,您的 doSomething 回调将以 MouseEvent 作为参数调用,但如果您不打算使用它,请不要担心。