[英]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,并试图调用本地方法
register
中onopen
的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.