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

Agr*_*dha 5 reactjs

我必须在构造函数中调用函数作为从回调工作,我必须包含在构造函数中,但这在构造函数中是“未定义的”。

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

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

        })

        }
 moveToNextStep(){
this.props.jumpToNextStep(3);
}
Run Code Online (Sandbox Code Playgroud)

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

小智 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);
}
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助