我有一个拥有handleRecord
方法的视频组件类。在handleRecord
方法内部,有一个被调用的对象recorder
,它返回一个 blob 对象方法调用被调用stopRecording
。
无论返回什么,我都希望该值在视频组件中设置状态。但是this
在回调中指的是记录器对象,而不是组件本身。在回调中获取组件并使用recorder
对象的最佳实践是什么?
handleRecord() {
...
} else {
this.state.recordVideo
recorder.stopRecording(function() {
var blob = this.getBlob();
console.log(this) // <= this refers to recorder object not the component
});
}
}
您可以设置一个变量来引用组件,然后在函数内部使用它:
const component = this;
recorder.stopRecording(function() {
var blob = this.getBlob();
console.log(component);
});
这实际上将this
在引用组件时捕获值并将其缓存在 中component
,因此当您在回调函数中使用它时,this
将引用记录器对象,但component
将引用您的组件。
当然,如果您想使用箭头函数之类的东西,您可以直接引用该recorder
对象,该函数采用this
其封闭范围的值——即组件:
recorder.stopRecording(() => {
var blob = recorder.getBlob();
console.log(this) // <= this refers to component
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句