2016-09-07 8 views
1

画面の向き(縦/横)が変更されたときに内容が変化するコンポーネントを作成しようとしています。これは私がやっているものです:ReactJSの画面方向の変更を処理する

姿勢変更イベントが発生したときの状態が変異していることを確認する方法
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')); 

+0

問題は何ですか?向きが変わったときにhandleChangeを呼び出す方法がわからないのですか?または、他の何か? – lustoykov

答えて

1

this.setStateへのお電話は間違っています。次のように変更する必要があります。

handleChange: function() { 
    var self = this;   // Store `this` component outside the callback 
    if ('onorientationchange' in window) { 
     window.addEventListener("orientationchange", function() { 
      // `this` is now pointing to `window`, not the component. So use `self`. 
      self.setState({ 
       orientation: !self.state.orientation 
      }) 
      console.log("onorientationchange"); 
     }, false); 
    } 
+0

ありがとうございます。 this.handleChangeをどこで呼び出すべきですか? –

+0

コンポーネントがマウントされているときに呼び出すことができます:['componentDidMount'](https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount)。 – Joy

+0

これはメモリリークを引き起こします。あなたのコールバックに太い矢印を使用するか、これを何とか関数にバインドする必要があります。 –

関連する問題