默认情况下,我在react-native项目中创建的每个屏幕都使用非常浅的灰色作为背景颜色。正如你在这里看到的:
我想知道,我不是为项目的每个屏幕设置
backgroundColor
,而是在反应原生项目中是否有一个全局位置,我可以为项目中的所有屏幕设置 backgroundColor
一次?例如,我希望我的所有屏幕都使用蓝色作为背景色。
由于您已经在使用react-navigation,它有一个主题提供程序,您可以提供自定义主题,代码如下所示,
import * as React from 'react';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';
const MyTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
primary: 'rgb(255, 45, 85)',
background:'red'
},
};
export default function App() {
return (
<NavigationContainer theme={MyTheme}>{/* content */}</NavigationContainer>
);
}
您可以查看文档以获取更多信息
在堆栈导航器中,您可以使用
更改它<Stack.Navigator screenOptions={{ contentStyle: {backgroundColor: '#f6f6f6f'}}}>
注意:#f6f6f6f 是红色的颜色代码,您可以根据您的要求更改它,下面是额外的代码片段,以防万一
const Stack = createNativeStackNavigator();
export default function App() {
return (
<>
<StatusBar style='auto' />
<NavigationContainer>
<Stack.Navigator screenOptions={{ contentStyle: {backgroundColor: '#f6f6f6f'}}}>
<Stack.Screen name="List Page" component={ListPage} />
<Stack.Screen name="List Page 2" component={ListPage} />
</Stack.Navigator>
</NavigationContainer>
</>
);
}
我更喜欢使用react-native-global-props: https://www.npmjs.com/package/react-native-global-props 非常简单:安装、导入和声明。
import { setCustomText } from 'react-native-global-props';
在最高阶组件中声明它。
const customViewProps = {
style: {
backgroundColor: '#d3d3d3' // light gray
}
};
setCustomView(customViewProps);
现在适用于您应用程序中的所有
View
。