我想使用所有主要移动浏览器都 支持 的事件 orientationchange
检测屏幕方向变化。
我在 componentDidMount
中添加事件侦听器,并从事件回调内部设置状态。
但是,我看到当事件由于从纵向更改为横向而首次触发时,状态不会更新为横向。然后,当我将方向从横向改回纵向时,状态显示方向为横向。此后每次我改变方向时,状态总是与实际方向相反。我不确定我是否应该使用某种生命周期反应方法,或者我的检测效果不好。
我使用 Chrome 开发人员工具 Toggle device toolbar
测试了代码。这是我的代码:
import React from 'react';
class AppInfo extends React.Component {
state = {
screenOrientation: 'portrait'
}
isPortraitMode = () => {
console.log(this.state);
const { screenOrientation } = this.state;
return screenOrientation === 'portrait';
}
setScreenOrientation = () => {
if (window.matchMedia("(orientation: portrait)").matches) {
console.log('orientation: portrait');
this.setState({
screenOrientation: 'portrait'
});
}
if (window.matchMedia("(orientation: landscape)").matches) {
console.log('orientation: landscape');
this.setState({
screenOrientation: 'landscape'
});
}
}
componentDidMount() {
window.addEventListener('orientationchange', this.setScreenOrientation);
}
render() {
console.log(`orientation: from render: isPortraitMode = ${this.isPortraitMode()}`);
<div>
Hello
</div>
}
}
export default AppInfo;
原文由 hitchhiker 发布,翻译遵循 CC BY-SA 4.0 许可协议