如何在 Material Top Tab Navigator 中为屏幕添加静态背景图片?

How to add a static background image for screens in Material Top Tab Navigator?

我使用 react-navigation 中的 createMaterialTopTabNavigator 创建了两个选项卡。我喜欢为两个选项卡设置一个背景图片。

当前的行为是,当我从 tab1 滑动到 tab2 时,图像也会转换,但我喜欢在从 tab1 转换到 tab2 时让背景图像静态,并且只有 tab 的内容在转换时刷了。我试过将 TabNavigator 包装在 ImageBackground 组件中,但没有用。

我认为您可以使用以下解决方案之一:

  1. 将选项卡设置为 透明背景 并将背景图像设置在导航器上方的 <View> 上。您可以在 React Navigation 文档中找到有关样式卡的详细信息 here
  2. 第二种选择,也是我认为更优雅的选择,是使用专用库来管理 React Navigation 中的转换。有一些,但我个人使用 Fluid Transitions 并且我喜欢它。如果您决定使用这个库,您可以在 StackNavigator 视图中设置背景图片。您将需要添加一个 shared 道具,然后您就完成了:)

这是演示:https://snack.expo.io/@nomi9995/e05080

使用 react-native-tab-view 并将 TabView 包装在 ImageBackground

中的更好方法
yarn add react-native-tab-view
import React, { Component } from "react";
import {
  Text,
  StyleSheet,
  View,
  SafeAreaView,
  ImageBackground,
  Dimensions,
} from "react-native";
import { TabView, SceneMap } from "react-native-tab-view";
const width = Dimensions.get("window").width;

function FirstRoute() {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>FirstRoute!</Text>
    </View>
  );
}

function SecondRoute() {
  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Text>SecondRoute!</Text>
    </View>
  );
}

export default class App extends Component {
  state = {
    index: 0,
    routes: [
      { key: "first", title: "First" },
      { key: "second", title: "Second" },
    ],
  };
  render() {
    const { index, routes } = this.state;
    const renderScene = SceneMap({
      first: FirstRoute,
      second: SecondRoute,
    });
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <ImageBackground
          style={{ flex: 1, width: width }}
          source={{
            uri:
              "https://firebasestorage.googleapis.com/v0/b/ielts-preps.appspot.com/o/1592920135765?alt=media&token=ec911583-06f9-4315-b66c-cf47de120e85",
          }}
        >
          <TabView
            navigationState={{ index, routes }}
            renderScene={renderScene}
            onIndexChange={(i) => this.setState({ index: i })}
            tabBarPosition="bottom"
          />
        </ImageBackground>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({});