我正在使用 React Native 和 React Native for Web 创建一个项目,以利用移动应用程序和网站的单一代码库。
我正在与 ScrollView 作斗争。它似乎在移动设备上可以正确滚动,但在网络上却不能。我创建了一些虚拟演示代码来显示此错误。我已经尝试过使用 Flex,但它似乎仍然不起作用。
// App.js
import { SafeAreaView, StatusBar } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import TestScreen from './screens/TestScreen';
const Stack = createStackNavigator();
export default function App() {
return (
<SafeAreaView style={{flex: 1}}>
<NavigationContainer>
<StatusBar style="auto"/>
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="Test" component={TestScreen} />
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>);}
//测试.js
import React from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
export default function HomeScreen() {
return (
<ScrollView>
<View style={styles.box}>
<Text>Box 1</Text>
</View>
<View style={styles.box}>
<Text>Box 2</Text>
</View>
<View style={styles.box}>
<Text>Box 3</Text>
</View>
<View style={styles.box}>
<Text>Box 4</Text>
</View>
<View style={styles.box}>
<Text>Box 5</Text>
</View>
<View style={styles.box}>
<Text>Box 6</Text>
</View>
</ScrollView>);}
const styles = StyleSheet.create({
box: {
height: 200,
margin: 20,
backgroundColor: 'skyblue',
justifyContent: 'center',
alignItems: 'center',
},
});
这是由于 createStackNavigator() 的默认行为,如果不需要,那么您可以选择 createNativeStackNavigator(),否则如果您必须使用 createStackNavigator() 那么您可以通过进行一些更改来修复此问题您的屏幕声明代码。
添加cardStyle: { flex: 1 } 这将解决你的问题
在导航器屏幕中添加此选项以应用于所有屏幕或添加到特定屏幕,这取决于您。
import { SafeAreaView, StatusBar } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import TestScreen from './screens/TestScreen';
const Stack = createStackNavigator();
export default function App() {
return (
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
<StatusBar style="auto" />
<Stack.Navigator screenOptions={{
headerShown: false,
cardStyle: {
flex: 1
}
}}>
<Stack.Screen name="Test" component={TestScreen} />
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>);
}
其他解决方案
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
官方文档,如果您想了解更多,仅供参考。 https://reactnavigation.org/docs/stack-navigator#cardstyle