我试图在我的 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
在 typeof 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/