反应导航;在标题中使用图像? [英] React Navigation; use image in header?

查看:50
本文介绍了反应导航;在标题中使用图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React Native 项目中使用 React 导航,我想用图片自定义标题.

I'm using react navigation in a react native project and I want to customize the header with an image.

对于颜色,我可以使用简单的样式,但由于 React Native 不支持背景图片,我需要不同的解决方案.

For a color I can use simple styling, but since react native doesn't support background images I need a different solution.

推荐答案

更新:

从库的 v2 开始,有一个用于设置标题背景的特殊选项,即 headerBackground.

Since v2 of the library there's an special option for setting the header background, namely headerBackground.

此选项接受一个 React 组件,因此当设置为 Image 组件时,它将使用它.

This option accepts a React component, so when set to an Image component, it will use that.

例如:

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 时:

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

Creating a custom header with an image is actually really simple.

通过用视图包裹 Header 并在该视图中放置一个绝对定位的图像,图像将缩放到其父尺寸.

By wrapping the Header with a view and placing an absolute positioned image in that view, the image will scale to its parent size.

重要的是将默认header的backgroundColor设置为transparent.

Important is to set the backgroundColor of the default header to 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>
);

然后将该组件用作标题:

And then use that component as header:

const SimpleStack = StackNavigator({
  Home: {
    screen: MyHomeScreen,
  },
}, {
  navigationOptions: {
    headerTitleStyle: { color: '#fff' },
    header: (props) => <ImageHeader {...props} />,
  }
});

这将导致:

这篇关于反应导航;在标题中使用图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆