处理 ReactJS 中的屏幕方向变化

Vis*_*oor 6 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'));
Run Code Online (Sandbox Code Playgroud)

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

Joy*_*Joy 5

你的调用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);
    }
Run Code Online (Sandbox Code Playgroud)

  • 这会导致内存泄漏。您应该在回调中使用粗箭头或以某种方式将其绑定到函数。 (2认同)