reactjs - 在 React 中动态调用方法

标签 reactjs react-native methods dynamic

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

所以我有这段代码,我想在其中调用函数stepOne , stepTwo等,只要实现了该步骤,但这需要动态调用以在将来添加新步骤。

但是我已经尝试了几种方法( 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>'
    }
}

在这个例子中,我总是得到 undefinedtypeof this[methodName]手术

最佳答案

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

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

关于reactjs - 在 React 中动态调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600149/

相关文章:

javascript - getInitialState() 替换现有状态。如何在 React 中传递现有状态?

javascript - 如何使用 {flip : false}? 选择退出 'rtl'

javascript - 如何防止第二次输入相同的字符

react-native - native 基础页脚接受玩家在 native react 中的触摸

java - 在方法之间传递变量?

Android 不按顺序调用方法

javascript - ReactJS:让函数同时访问父子 Prop ?

javascript - react 导航 goBack() 并在上一个屏幕中更新

Java 类方法、方法 invoke() 和原始类型

react-native - 使图像填充父级,但在 react 原生(动态/网络图像)中保持比例