代码之家  ›  专栏  ›  技术社区  ›  Abraham Romero

在react中动态调用方法

  •  1
  • Abraham Romero  · 技术社区  · 6 年前

    我尝试在我的react组件中动态调用一些方法。

    所以我有一个代码,我想调用一个函数 stepOne , stepTwo 等。只要实现了该步骤,就需要动态调用它以在将来添加新步骤。

    但是我已经尝试了两种方法( hasOwnProperty , typeof this[methodName] , this.{methodName}() )无法调用正确的方法。

    这是我的代码:

    class MyComponent extends React.Component<Props,State>{
    
        steps = [
            'stepOne',
            'stepTwo',
            'stepThree',
        ];
    
        state = {step:1};
    
        stepOne(){
            return 'This is Step One';
        }
    
        stepTwo(){
            return 'This is Step Two';
        }
    
        _getContent(){
            let content = 'Step not exists';
    
            const methodName = this.steps[this.state.step - 1];
    
            if (typeof this[methodName] === 'function') {
                content = this[methodName]();
            }
            return content;
        }
    
        render(){
            return '<div>' + this._getContent() + '</div>'
        }
    }
    

    在这个例子中,我总是 undefined 此类型[方法名] 操作

    1 回复  |  直到 6 年前
        1
  •  1
  •   Suresh Prajapati    6 年前

    class MyComponent extends React.Component<Props,State>{
        constructor(props){
            super(props);
            this.stepOne = this.stepOne.bind(this);
            this.stepTwo = this.stepTwo.bind(this);
            this.funcMap = {
                '1': this.stepOne,
                '2': this.stepTwo
            };
            this.state = {step: '1'};
        }
    
    
        stepOne(){
            return 'This is Step One';
        }
    
        stepTwo(){
            return 'This is Step Two';
        }
    
        _getContent(){
            let content = 'Step not exists';
    
            const method = this.funcMap[this.state.step];
    
            if (typeof method === 'function') {
                content = method();
            }
            return content;
        }
    
        render(){
            return '<div>' + this._getContent() + '</div>'
        }
    }