首页 > 解决方案 > 如何更改 react-native-tab-view 的颜色?

问题描述

我是 react-native 和学习它的新手。在学习 react-native-tab-view 时,我尝试更改它的颜色,但经过几次尝试我无法做到。如果有人指导我如何更改默认为蓝色的标签栏颜色,我将不胜感激。这是 npm react-native-tab-view 的链接,这是一段代码。任何帮助将不胜感激。

import * as React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
 
const FirstRoute = () => (
  <View style={[styles.scene, { backgroundColor: '#ff4081' }]} />
);
 
const SecondRoute = () => (
  <View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
 
const initialLayout = { width: Dimensions.get('window').width };
 
export default function TabViewExample() {
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: 'first', title: 'First' },
    { key: 'second', title: 'Second' },
  ]);
 
  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
  });
 
  return (
    <TabView
      navigationState={{ index, routes }}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={initialLayout}
    />
  );
}
 
const styles = StyleSheet.create({
  scene: {
    flex: 1,
  },
});

标签: react-nativereact-native-tab-view

解决方案


更改标签栏的背景颜色

如果您参考本,则必须在使用该属性声明自定义 React 组件后传递标签栏的样式属性renderTabBar

<TabView
  navigationState={{ index, routes }}
  renderScene={renderScene}
  onIndexChange={setIndex}
  initialLayout={initialLayout}
  renderTabBar={props => <TabBar {...props} style={{backgroundColor: 'black'}}/>} // <-- add this line
/>

更改标签栏的文本颜色

如果你参考这个,

<TabBar
  renderLabel={({route, color}) => (
    <Text style={{ color: 'black', margin: 8 }}>
      {route.title}
    </Text>
  )}
  style={{backgroundColor: 'white'}}
  ...
/>

随意使用示例小吃进一步试验。:)


推荐阅读