问题描述
我有一个方法'joinRoom',它是使用fat aero创建的,所以我认为我不需要传递'this'作为参数或绑定它。这很明显,但是我想将joinRoom函数存储在另一个文件中,但是该文件(用于模块化方法并保持我的此文件干净)包含'this'关键字。如何处理该模块中的“ this”关键字?检查下面的代码
main.js
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
}
this.socket = null
}
joinRoom = () => joinRoom() //this one
render() {
return();
}
}
whoisOnline.js
whoisOnline = () => {
sendToPeer('onlinePeers',null,{local: this.socketID})
}
我只想将所有方法保留在该类的另一个模块中,但是它们都涉及'this'关键字,如何处理这种情况,请事先告知我。
解决方法
我只是试图找到一条出路,我必须将'this'作为参数传递,以便该对象在函数中可用,然后在函数中可以使用它。
main.js
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
}
this.socket = null
}
joinRoom = () => joinRoom(this) //passed 'this' keyword
render() {
return();
}
}
whoisOnline.js
whoisOnline = (object) => { // passed object argument and then used it to access 'this' from the calss
sendToPeer('onlinePeers',null,{local: object.socketID})
}