如何在websocket事件中使用bind(this)调用方法

时间:2017-07-28 05:55:24

标签: reactjs bind

我正在使用React和Websocket来测试通信:

class Class extends React.Component {

  constructor(props) {
    super(props);
    this.state = {...};
    this.generateMsg= this.generateMsg.bind(this);
    this.sendMsg = this.sendMsg.bind(this);
  }

  //generate a random array
  generateMsg(n) {return [...]}

  //websocket sendMsg
  sendMsg(){
    const wsClient = new Websocket(url);
    wsClient.onopen = function(){
      wsClient.send(this.generateMsg(40));
    }
  }

  render() {
    return (
      <button onClick={this.sendMsg}>{this.state.nameList}</button>
    );
  }
}

ReactDOM.render(...);

总是引发错误&#34; this.generateMsg不是函数&#34;,如何在websocket事件中调用带有bind(this)的方法?

2 个答案:

答案 0 :(得分:1)

使用箭头功能:

    wsClient.onopen = () => {
      wsClient.send(this.generateMsg(40));
    }

答案 1 :(得分:0)

为什么要在每个sendMsg调用上创建新的WebSocket连接?您可以在class Class extends React.Component { constructor(props) { super(props); this.state = {...}; this.generateMsg = this.generateMsg.bind(this); this.sendMsg = this.sendMsg.bind(this); } // open connection on mount componentDidMount() { this.socket = new WebSocket(url); } //generate a random array generateMsg(n) {return [...]} //websocket sendMsg sendMsg() { this.socket.send(this.generateMsg(40)); } render() { return ( <button onClick={this.sendMsg}>{this.state.nameList}</button> ); } } 上打开连接并存储它。

<div ng-if="$eval(condition)"></div>