我正在尝试创建一个组件,当屏幕方向(纵向/横向)发生变化时,其内容会发生变化。这就是我在做的事情:
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 :(得分: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);
}