我有一个类应用程序在 react
class App extends Component
在 componentWillMount()
中,我已经初始化了套接字 this.socket = io();
。
现在,如果我在 componentWillMount 之外的另一个函数中使用套接字,我会收到一个错误,例如 anotherfunction(){
this.socket.emit('welc_message','你好');
}
我收到
Uncaught TypeError: Cannot read property 'emit' of undefined
最佳答案
解决方案是在构造函数部分中我们绑定(bind) anotherfunction 的上下文,因此我们通过 this.anotherfunction = this.anotherfunction.bind(this)
这是整个应用程序文件夹的样子 App.js
关于javascript - 在扩展 react 组件中绑定(bind)套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39599892/