反应中组件构造函数内部的调用函数?

时间:2018-05-09 06:19:09

标签: reactjs

我必须在构造函数中调用函数作为回调函数,我必须在构造函数中包含它,但这是" undefined"在构造函数中。

class XXXXX extends React.Component {
        constructor(props) {
            super(props);
            thisstate = 
            {
                chargebeeInstance : windowChargebeeinit({
                site: "xxxxxxxxxxxxx-test"})
            }

            thisstatechargebeeInstancesetCheckoutCallbacks(function(){
                return{
                    close:function(){
                    this.moveToNextStep();
                }
            }

        })

        }
 moveToNextStep(){
this.props.jumpToNextStep(3);
}

我无法调用moveToNextStep,因为这是未定义的

2 个答案:

答案 0 :(得分:3)

这是范围问题,您必须在下面提到的this.statechargebeeInstancesetCheckoutCallbacks功能之前保留范围

class XXXXX extends React.Component {
    constructor(props) {
        super(props);
        const me = this
        this.state = 
        {
            chargebeeInstance : windowChargebeeinit({
            site: "xxxxxxxxxxxxx-test"})
        }

        this.statechargebeeInstancesetCheckoutCallbacks(function(){
            return{
                close:function(){
                me.moveToNextStep();//scope issue, this will not be available here
            }
        }

    })

    }
 moveToNextStep(){
    this.props.jumpToNextStep(3);
}

希望这会有所帮助

答案 1 :(得分:0)

您需要将函数绑定到当前闭包。试试这个:

class XXXXX extends React.Component {
  constructor(props) {
   super(props);

   // I believe this is what you are missing.
   this.moveToNextStep = this.moveToNextStep.bind(this)

   this.state = {
     chargebeeInstance : windowChargebeeinit({
       site: "xxxxxxxxxxxxx-test"
     })
   }

   this.statechargebeeInstancesetCheckoutCallbacks(function(){
    return{
      close:function(){
        this.moveToNextStep();
       }
     }
   })
  }

  moveToNextStep(){
   this.props.jumpToNextStep(3);
  }
}