简体   繁体   English

在React.js组件的websocket的onopen事件中调用函数

[英]calling function in onopen event of websocket in React.js component

I am using websocket in React.js component, and trying to call a local method register in onopen event of websocket. 我正在使用React.js组件的WebSocket,并试图调用本地方法registeronopen的WebSocket的事件。 console.log() is working ok inside onopen event, but my local function register is not. console.log()在onopen事件中可以正常工作,但是我的本地功能register不起作用。 I am getting errror register is not a function . 我正在获得错误登记不是功能

Here is the code 这是代码

this.ws.onopen = function()
{
  console.log('Connected! now registering');
  this.register();
}

Any help! 任何帮助!

That's because the value of this is changing. 这是因为值this正在发生变化。 What's happening is you're assigning a function to this.ws.onopen , and then the web socket instance is invoking onopen where this points to the web socket itself, and not your reactjs class instance. 发生了什么事是你分配一个功能this.ws.onopen ,然后web套接字实例调用onopen其中this指向网络插座本身,而不是你的reactjs类的实例。 You need to preserve a reference to your reactjs class instance and use that to invoke the register method: 您需要保留对reactjs类实例的引用,并使用该引用来调用register方法:

this.ws.onopen = () =>
{
  console.log('Connected! now registering');
  this.register();
}

The above uses arrow functions (an ECMA6 feature) to preserve the value of this. 上面使用箭头功能(ECMA6功能)保留此值。 This works because arrow functions don't allow their caller (in this case the web socket) to change their value of this . 之所以可行,是因为箭头函数不允许其调用者(在本例中为Web套接字)更改其this的值。 Or you can do: 或者,您可以执行以下操作:

var self = this;
this.ws.onopen = function()
{
  console.log('Connected! now registering');
  self.register();
}

which simply stores a reference to your reactjs object prior to executing the function where the value for this gets changed. 它简单地存储基准之前执行,其中用于值的函数到您reactjs对象this得到改变。 Or you can do: 或者,您可以执行以下操作:

this.ws.onopen = function()
{
  console.log('Connected! now registering');
  this.register();
}.bind(this)

which, prior to assigning a function to the property this.ws.onopen asserts that no matter who or how the function is called, the value of this for the function will always be whatever you passed to .bind . 在将函数分配给属性this.ws.onopen之前,该函数断言无论调用该函数的人或方式如何,函数的this值始终是您传递给.bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM