Handling the screen orientation change in ReactJS -
i trying create component content changes when screen orientation(portrait/landscape) changes. doing:
var greeting = react.createclass({ getinitialstate: function() { return {orientation: true} }, handlechange: function() { if ('onorientationchange' in window) { window.addeventlistener("orientationchange", function() { this.setstate({ orientation: !this.state.orientation }) console.log("onorientationchange"); }, false); } else if ('onresize' in window) { window.addeventlistener("resize", function() { this.setstate({ orientation: !this.state.orientation }) console.log("resize"); }, false); } }, render: function() { var message = this.state.orientation ? "hello" : "good bye" return <p>{message}</p>; } }); reactdom.render( <greeting/>, document.getelementbyid('container'));
how make sure state mutated when orientation change event fired .
your calling this.setstate
wrong. need change like:
handlechange: function() { var self = this; // store `this` component outside callback if ('onorientationchange' in window) { window.addeventlistener("orientationchange", function() { // `this` pointing `window`, not component. use `self`. self.setstate({ orientation: !self.state.orientation }) console.log("onorientationchange"); }, false); }
Comments
Post a Comment