在本机反应中制作滑块导航的最佳方法

sam*_*uel 3 navigation android react-native expo

我尝试在react-native中重新创建此应用程序:

在此输入图像描述

但我没有任何制作红色组件的线索。我在互联网上搜索,发现了react-navigation V5,但它看起来很复杂。

我还想创建一个水平的ScrollView,每次单击新的“页面”时,都会重新渲染所有当前视图。但这是个好办法吗?

感谢您的回答。

Bas*_*den 5

我喜欢 @mainak 使用 的建议react-native-tab-view。为了补充这个答案,我做了一个简单的实现来完成你想要的事情。

首先安装库:yarn add react-native-tab-viewnpm i react-native-tab-view --save.

然后你可以做这样的事情:

// ...
import {TabView, SceneMap, TabBar} from 'react-native-tab-view';
// ...

const initialLayout = {width: Dimensions.get('window').width};

const renderTabBar = (props) => (
  <TabBar
    {...props}
    tabStyle={{width: 120}}
    scrollEnabled={true}
    indicatorStyle={{backgroundColor: 'white', height: 5, borderRadius: 10}}
  />
);

const App = () => {
  // ...
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    {key: 'first', title: 'First'},
    {key: 'second', title: 'Second'},
    {key: 'third', title: 'Third'},
    {key: 'fourth', title: 'Fourth'},
    {key: 'fifth', title: 'Fifth'},
  ]);

  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
    third: ThirdRoute,
    fourth: FourthRoute,
    fifth: FifthRoute,
  });

  return (
    <TabView
      navigationState={{index, routes}}
      renderTabBar={renderTabBar}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={initialLayout}
    />
  );
};


const styles = StyleSheet.create({
  scene: {
    flex: 1,
  },
});
Run Code Online (Sandbox Code Playgroud)

FirstRoute我已经定义了名为、等的视图组件SecondRoute...但是将其更改为您想要在选项卡栏中显示的屏幕。

这里的关键部分是renderTabBarTabBar传递给TabView组件的自定义组件。在组件上,TabBar我们有一个选项scrollEnabled,如果设置为 true,则允许我们根据选项卡视图和选项卡的大小从左向右滚动栏。

我已经为每个选项卡定义了宽度120,但您可能需要根据选项卡标签的大小来使用该值。

您引用的活动选项卡栏下方的红色突出显示称为指示器,可以使用indicatorStyleprop 进行样式设置:

indicatorStyle={{backgroundColor: 'white', height: 5, borderRadius: 10}}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅 github 页面上的文档: https: //github.com/satya164/react-native-tab-view