处理ReactJS中的屏幕方向更改

时间:2016-09-07 12:33:23

标签: 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'));

如何在触发方向更改事件时确保状态发生变化。

1 个答案:

答案 0 :(得分:2)

您对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);
    }