如何仅针对特定视图禁用旋转(例如:使用Navigator时)而不是整个应用程序?
问题here已经解决了停止整个应用的轮播问题
答案 0 :(得分:3)
使用react-native-orientation
包裹,可以将方向锁定为纵向/横向。包和文档可以在这里找到:https://github.com/yamill/react-native-orientation
记住;你不应该把你的锁定放在场景的渲染中(也不是renderScene
方法)。由于导航器重新渲染路径堆栈中的所有场景,这可能会给您带来奇怪的副作用。相反,锁定/解锁应该放在与路由堆栈交互的代码中(即调用push
/ pop
方法)。
答案 1 :(得分:1)
如果您的情况是要更具体地控制StackNavigator中不同屏幕的方向(例如Portrait -> LandscapeLeft -> LandscapeRight -> Portrait
,然后一直返回),这是一个可能并非如此的解决方案:
定义基本屏幕,如下所示:
// baseScreen.js
import React, { Component } from "react";
import Orientation from "react-native-orientation";
export class PortraitScreen extends Component {
constructor(props) {
super(props);
this._willFocusSubscription = this.props.navigation.addListener("willFocus", payload => {
// lock to portrait when this screen is about to appear
Orientation.lockToPortrait();
})
}
componentWillUnmount() {
// remove subscription when unmount
this._willFocusSubscription.remove();
}
}
export class LandscapeScreen extends Component {
constructor(props) {
super(props);
this._willFocusSubscription = this.props.navigation.addListener("willFocus", payload => {
// lock to landscape
Orientation.lockToLandscape();
})
}
componentWillUnmount() {
// remove subscription either
this._willFocusSubscription.remove();
}
}
定义延伸上述基础屏幕的混凝土屏幕:
// moduleScreens.js
import React from "react";
import { Button, View } from "react-native";
import { PortraitScreen, LandscapeScreen } from "/path/to/baseScreen";
export class VideoDescScreen extends PortraitScreen {
render() {
return (
<View>
<Button
title="watch video"
onPress={() => this.props.navigation.navigate("VideoPlayer")}
/>
</View>
)
}
}
export class VideoPlayerScreen extends LandscapeScreen {
render() {
return <View>...</View>
}
}
创建这样的路线:
// route.js
import React from "react";
import { createStackNavigator } from "react-navigation";
import { VideoDescScreen, VideoPlayerScreen } from "/path/to/moduleScreens";
const stack = createStackNavigator(
{
VideoDesc: {
screen: VideoDescScreen
},
VideoPlayer: {
screen: VideoPlayerScreen
}
}
)
它如何工作?根据{{3}},我们在初始化屏幕时观察到事件willFocus
,并且每次该屏幕即将出现在导航中(聚焦)时,我们都将设备锁定在所需的方向,这对两个PUSH( )和POP(发回)行为。
希望有帮助。