![](/img/trans.png)
[英]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.