处理ReactJS中的屏幕方向更改

7
我正在尝试创建一个组件,在屏幕方向(纵向/横向)更改时,其内容也会更改。这是我的做法:
 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'));

如何确保状态在方向变化事件被触发时进行了改变。

问题是什么?你不知道如何在方向改变时调用handleChange吗?还是其他什么问题? - Lyubomir
1个回答

6

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

谢谢。我应该在哪里调用this.handleChange? - Diablo3093
当组件被挂载时,您可以调用它:componentDidMount - Joy
2
这会导致内存泄漏。你应该在回调函数上使用箭头函数或以某种方式将this绑定到函数上。 - Aditya Nagrath
1
现在已经取消了orientationchange支持。 - Sujit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接