reactjs - How to call method with bind(this) inside a websocket event -
i using react , websocket test communication:
class class extends react.component { constructor(props) { super(props); this.state = {...}; this.generatemsg= this.generatemsg.bind(this); this.sendmsg = this.sendmsg.bind(this); } //generate 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(...);
always raises err "this.generatemsg not function", how call method bind(this) inside websocket event please?
use arrow function this:
wsclient.onopen = () => { wsclient.send(this.generatemsg(40)); }
Comments
Post a Comment