React:我如何在另一个自定义函数中运行一个自定义函数

时间:2019-08-03 19:00:35

标签: reactjs

我想通过自定义函数重用react组件中的某些代码。但是,当我运行以下代码时,出现错误:this.runBubbles()未定义。

class HomePage extends React.Component {

  runBubbles(){
    // instantiate some css bubbles on screen
  }

  clearAndRunBubbles(){
    // clear bubbles from DOM
    this.runBubbles()
  }

  componentDidMount(){
    this.runBubbles()
    // on resize, re-run bubbles code with new screen dimensions:
    window.addEventListener("resize",this.clearAndRunBubbles);
  }
}

2 个答案:

答案 0 :(得分:1)

尝试这样

class HomePage extends React.Component {

  runBubbles = () => {
    // instantiate some css bubbles on screen
  }

  clearAndRunBubbles = () =>  {
    // clear bubbles from DOM
    this.runBubbles()
  }

  componentDidMount(){
    this.runBubbles()
    // on resize, re-run bubbles code with new screen dimensions:
    window.addEventListener("resize", this.clearAndRunBubbles);
  }
}

对于箭头功能,您不需要具有此绑定,因为默认情况下,它需要外部词法作用域。

class HomePage extends React.Component {

 constructor() {
   this.runBubbles = this.runBubbles.bind(this);
   this.clearAndRunBubbles = this. clearAndRunBubbles.bind(this);
 }

runBubbles(){
    // instantiate some css bubbles on screen
  }

  clearAndRunBubbles(){
    // clear bubbles from DOM
    this.runBubbles()
  }

  componentDidMount(){
    this.runBubbles()
    // on resize, re-run bubbles code with new screen dimensions:
    window.addEventListener("resize",this.clearAndRunBubbles);
  }
}

每当在react中调用类组件内部的标准函数时,您都必须添加此绑定,以确保该函数绑定到当前类组件。

答案 1 :(得分:0)

componentDidMount方法上,将runBubbles()更改为this.runBubbles()

相关问题