我尝试在我的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
在
此类型[方法名]
操作