传递给反应组件 children 的函数不接收函数上下文

Functions passed to react component children don't receive function context

我在使用 React 时卡住了,其中,我将一个函数从 parent 组件传递给多个 children 组件。该函数调用也驻留在 parent 组件中的其他函数。

children 组件确实成功启动了该功能,但不幸的是,该功能失败了,因为它似乎在 children 的元素中没有相同的上下文,例如。它开始调用存储在 parent 元素中的其他函数,并接收未定义的。这很奇怪,因为错误来自 parent 组件文件,而不是 child 组件文件。

我不确定是否将所有函数都传递给 children 元素,这感觉相当笨重,而且感觉我仍然会缺少重要的函数上下文。

我已经在 parent 组件上测试了 运行 相同的功能,它没有任何问题,几乎就像 parent 组件的功能上下文没有传递给 child组件,只有函数本身。

对吗?

这是一个示例,其中 child 组件有一个按钮可以单击,该按钮将 运行 从 parent 组件传递并包含 运行ning 的函数parent 组件中的其他功能,更新状态和进行更改等

Parent 元素:

class Content extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "React",
      toggle: true,
      ...
    };
  }
  toggleComponent(name) {
      this.toggling(name); // THIS IS WHERE THE ERROR OCCURS ON THE CHILD ELEMENT, undefined.
  }
  toggling(name) {
      does some stuff...
  }

  render() {
   return (
    <Comp toggleComponent={this.toggleComponent}/>
   )
  }

Child 元素:

class Demo1 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "React"
    };
  }

  render() {
    return (
       <div className="button" onClick={() => this.props.toggleComponent('theCompName')}>Continue</div>
    )

让我知道如何将附加上下文传递给 children 组件,或者是否有更好的方法。

谢谢,你们都很聪明。

在父组件的函数中使用箭头语法。这将允许父组件中的函数在父组件的上下文中执行。否则你将不得不做一堆 binding(this) 废话才能使它正常工作。

Content class 的构造函数中,尝试使用 .bind():

将 toggleComponent 函数绑定到 class
  constructor(props) {
    super(props);
    this.state = {
      name: "React",
      toggle: true,
      ...
    };

    this.toggleComponent = this.toggleComponent.bind(this);
  }
默认情况下,

Class 方法不是 "bound" 到 class。这意味着您在 toggleComponent 中的 this 关键字不会引用 Content class 直到您使用 .bind().

指定它

希望对您有所帮助!

可在此处找到更多信息:https://reactjs.org/docs/handling-events.html