在React

时间:2018-07-30 18:27:10

标签: reactjs react-native methods dynamic

我试图在React组件中动态调用一些方法。

所以我有这段代码,只要要实现此步骤,就想在其中调用函数stepOnestepTwo等,但是将来需要动态调用此函数以添加新的步骤。

但是我已经尝试了几种方法(hasOwnPropertytypeof 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操作中得到typeof this[methodName]

1 个答案:

答案 0 :(得分:1)

尝试创建函数映射,并将此上下文绑定到您创建的函数

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>'
    }
}