[英]Calling function defined within a react function component on a click event form another function component - React.js
[英]calling function in onopen event of websocket in React.js component
我正在使用React.js组件的WebSocket,并试图调用本地方法register
中onopen
的WebSocket的事件。 console.log()
在onopen事件中可以正常工作,但是我的本地功能register
不起作用。 我正在获得错误登记不是功能 。
这是代码
this.ws.onopen = function()
{
console.log('Connected! now registering');
this.register();
}
任何帮助!
这是因为值this
正在发生变化。 发生了什么事是你分配一个功能this.ws.onopen
,然后web套接字实例调用onopen
其中this
指向网络插座本身,而不是你的reactjs类的实例。 您需要保留对reactjs类实例的引用,并使用该引用来调用register
方法:
this.ws.onopen = () =>
{
console.log('Connected! now registering');
this.register();
}
上面使用箭头功能(ECMA6功能)保留此值。 之所以可行,是因为箭头函数不允许其调用者(在本例中为Web套接字)更改其this
的值。 或者,您可以执行以下操作:
var self = this;
this.ws.onopen = function()
{
console.log('Connected! now registering');
self.register();
}
它简单地存储基准之前执行,其中用于值的函数到您reactjs对象this
得到改变。 或者,您可以执行以下操作:
this.ws.onopen = function()
{
console.log('Connected! now registering');
this.register();
}.bind(this)
在将函数分配给属性this.ws.onopen
之前,该函数断言无论调用该函数的人或方式如何,函数的this
值始终是您传递给.bind
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.