【发布时间】:2017-10-21 04:24:02
【问题描述】:
我在 react native 项目中使用 react 导航,我想用图像自定义标题。
对于颜色,我可以使用简单的样式,但由于 react native 不支持背景图片,我需要不同的解决方案。
【问题讨论】:
标签: reactjs react-native react-navigation
我在 react native 项目中使用 react 导航,我想用图像自定义标题。
对于颜色,我可以使用简单的样式,但由于 react native 不支持背景图片,我需要不同的解决方案。
【问题讨论】:
标签: reactjs react-native react-navigation
更新:
从库的 v2 开始,有一个用于设置标题背景的特殊选项,即headerBackground。
此选项接受 React 组件,因此当设置为 Image 组件时,它将使用该组件。
例如:
export default createStackNavigator({
Home: {
screen: HomeScreen
},
}, {
navigationOptions: {
headerBackground: () => (
<Image
style={StyleSheet.absoluteFill}
source={{ uri: 'https://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg' }}
/>
),
}
});
工作示例:https://snack.expo.io/@koen/react-navigation-header-background
旧答案,当仍在使用 React Navigation v1 时:
使用图像创建自定义标题实际上非常简单。
通过用视图包装 Header 并在该视图中放置绝对定位的图像,图像将缩放到其父大小。
重要的是设置默认头的backgroundColor为transparent。
const ImageHeader = props => (
<View style={{ backgroundColor: '#eee' }}>
<Image
style={StyleSheet.absoluteFill}
source={{ uri: 'https://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg' }}
/>
<Header {...props} style={{ backgroundColor: 'transparent' }}/>
</View>
);
然后将该组件用作标题:
const SimpleStack = StackNavigator({
Home: {
screen: MyHomeScreen,
},
}, {
navigationOptions: {
headerTitleStyle: { color: '#fff' },
header: (props) => <ImageHeader {...props} />,
}
});
这会导致:
【讨论】:
React Navigation v5 更新! (制作这篇文章以供将来参考)
对于反应导航 5,我找到了这个解决方案。
在 StackNavigator.js 类中,您可以为每个页面(Stack.Screen)设置不同的图像:
<Stack.Screen
name='Home'
component={HomeScreen}
options={{
title: <Image style={{ width: 250, height: 50 }}
source = require('../images/yourimage.png')}/>
}}
/>
然后,您必须调整图像的宽度、高度和位置,但它可以工作!我认为这是最简单的方法。这是输出(是的,这是我的图像,在调整之前)。
别忘了导入图片!
import { Image } from 'react-native'
【讨论】:
根据react-navigation v5的官方文档,可以如下实现:
https://reactnavigation.org/docs/headers/#replacing-the-title-with-a-custom-component
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
// title: 'App Name'
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: 200, height: 50 }}
source={require('../assets/images/app-logo-1.png')}
resizeMode='contain'
/>
),
headerTitleStyle: { flex: 1, textAlign: 'center' },
}}
/>
</Stack.Navigator>
【讨论】: