小编典典

反应导航;在标题中使用图片?

reactjs

我在react本机项目中使用react导航,并且想用图像自定义标题。

对于一种颜色,我可以使用简单的样式,但是由于react native不支持背景图像,因此我需要一个不同的解决方案。


阅读 268

收藏
2020-07-22

共1个答案

小编典典

更新:

从库的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的问题:

使用图像创建自定义标头实际上非常简单。

通过将标题与视图一起包装并在该视图中放置绝对定位的图像,该图像将缩放为其父尺寸。

重要的是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} />,
  }
});

这将导致:

2020-07-22