如何在 React Native 中更改自定义选项卡的文本颜色和图像

IT技术 reactjs image react-native text tabs
2021-05-10 07:27:45

我已将自定义标签栏添加到我的应用程序中。它位于屏幕中央。一次应激活一个选项卡。所以,我的自定义标签栏中有 4 个标签。默认情况下,我显示第一个选项卡处于活动状态,因此,我也显示活动文本(黑色)和图像。

如果用户点击第二个选项卡,第一个、第三个、第四个选项卡应处于非活动状态,并根据灰色文本显示非活动图像。

对于所有这些选项卡操作/处理程序,我创建了单个方法并传递了选项卡名称,据此我能够区分它们并执行任务。

这是我的代码

class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = { selectedLanguage: null}
  }

  onClick = (language) => { 
    this.setState({selectedLanguage: language}) 
  }

  renderBottomContent = () => {
    const {selectedLanguge} = this.state
    switch(selectedLanguage) {
      case "telugu":
        return <View><Text>Telugu</Text></View>
      case "tamil":
        return <View><Text>Tamil</Text></View>
      case "hindi":
        return <View><Text>Hindi</Text></View>
      case "english":
        return <View><Text>English</Text></View>
      default:
        return <View><Text>No Language Selected...</Text></View>
    }
  }

  render() { 
    <View style ={styles.tabInnerContainer}>
      <TouchableOpacity style={styles.tabIcons} onPress={() => this.onClick('telugu')}>
        <Image style={styles.tabItemsImages} source={image} />
      <Text style={styles.tabTextItems}>
        Telugu
      </Text>
      </TouchableOpacity>
    </View>
    <View style ={styles.tabInnerContainer}>
      <TouchableOpacity style={styles.tabIcons} onPress={() => this.onClick('tamil')}>
        <Image style={styles.tabItemsImages} source={image} />
      <Text style={styles.tabTextItems}>
        Tamil
      </Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.tabIcons} onPress={() => this.onClick('Hindi')}>
        <Image style={styles.tabItemsImages} source={image} />
      <Text style={styles.tabTextItems}>
        Telugu
      </Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.tabIcons} onPress={() => this.onClick('English')}>
        <Image style={styles.tabItemsImages} source={image} />
      <Text style={styles.tabTextItems}>
        Telugu
      </Text>
      </TouchableOpacity>
    </View>
... 
    // after all the other tab buttons, render bottom content depending on the component state
    {this.renderBottomContent()}
  }
}

在此处输入图片说明

有人建议我,如何根据活动和非活动状态更改所有选项卡文本和图像?

1个回答

你可以这样做:

render() { 
  const {selectedLanguge} = this.state;

  <View style ={styles.tabInnerContainer}>
    <TouchableOpacity style={styles.tabIcons} onPress={() => this.onClick('telugu')}>
      <Image style={[styles.tabItemsImages, selectedLangage === 'telugu' && styles.disabledImageStyle]} source={image} />
        <Text style={[styles.tabTextItems, selectedLangage === 'telugu' && styles.disabledTextStyle]}>
          Telugu
        </Text>
      </TouchableOpacity>
    </View>
    ...

然后您只需为禁用图像和禁用文本定义样式。它不是很 DRY,因为您需要为每个选项卡检查 selectedLanguage 两次,但它有效。