2017-07-09 85 views
0

我有一个视频组件类拥有一个handleRecord方法。在handleRecord方法中,有一个名为recorder的对象返回一个称为stopRecording的对象方法调用的blob。我如何获得此参考React组件?

无论返回什么,我都希望在视频组件中设置状态值。但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 
     }); 
    } 
} 

回答

1

您可以设置一个变量来引用该组件,然后用它里面的功能:

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 
}); 
+0

有趣的方法。 – MLhacker

+0

谢谢安德鲁。我想我喜欢第二种方法最好。检查这一点。 – MLhacker